美文网首页
NsetJS封装统一成功请求和失败请求

NsetJS封装统一成功请求和失败请求

作者: Poppy11 | 来源:发表于2021-07-03 17:39 被阅读0次

成功请求

1、创建拦截器

 nest g interceptor interceptor/transform

2、在TransformInterceptor文件代码

import {
  Injectable,
  NestInterceptor,
  CallHandler,
  ExecutionContext,
  PipeTransform,
  ArgumentMetadata,
  BadRequestException,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
interface Response<T> {
  data: T;
}
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext,next: CallHandler<T>,): Observable<Response<T>> {
    return next.handle().pipe(map(data => {
        return {
          data,
          code: 0,
          message: '请求成功',
        };
      }),
    );
  }
}

失败请求

1、创建异常过滤器

nest g filter filter/http-exception

2、HttpExceptionFilter代码

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const message = exception.message;
    Logger.log('错误提示', message);
    const errorResponse = {
      message: message,
      code: 1, // 自定义code
      url: request.originalUrl, // 错误的url地址
    };
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    // 设置返回的状态码、请求头、发送错误信息
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}

3、在main.ts中使用

 // 全局使用管道
  app.useGlobalPipes(new ValidationPipe());
  app.useGlobalInterceptors(new TransformInterceptor())
  app.useGlobalFilters(new HttpExceptionFilter());

相关文章

网友评论

      本文标题:NsetJS封装统一成功请求和失败请求

      本文链接:https://www.haomeiwen.com/subject/nufpultx.html