统一返回格式

{data:object,message:请求成功,code:200}

成功的格式

{
 "statusCode": 200,
  "data": {
    "username": "string",
    "access_token": "XXX"
  },
  "code": 0,
  "message": "请求成功"
}

失败的格式

{
  "statusCode": 401,
  "data": {
    "error": "Client Error"
  },
  "message": "请求失败",
  "code": 1,
  "url": "/api/auth/profile"
}

暂定code代表成功,1代表失败,成功data里是返回内容,失败data里是错误信息。

拦截全部的错误请求

src/core/filters/all-exception.filter’;

import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
import { Request, Response } from 'express';
@Catch()
export class AllExceptionFilter<T> implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message = exception.message.message
      ? exception.message.message
      : `${status >= 500 ? 'Service Error' : 'Client Error'}`;
    const errorResponse = {
      statusCode: status,
      data: { error: message },
      message: '请求失败',
      code: 1, // 自定义code
    };
    // 设置返回的状态码、请求头、发送错误信息
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}

拦截成功的返回数据

src/core/interceptors/response.interceptor’;

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Response } from 'express';
@Injectable()
export class ResponseInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const response = context.switchToHttp().getResponse<Response>();
    console.log(response.statusCode);
    return next.handle().pipe(
      map(data => {
        return {
          data,
          code: 0,
          message: '请求成功',
          statusCode: response.statusCode,
        };
      }),
    );
  }
}

全局注册

main.ts

...
import { TransformInterceptor } from './core/interceptor/transform.interceptor';

async function bootstrap() {
  ...
  // 全局注册拦截器
  app.useGlobalFilters(new AllExceptionFilter());
  app.useGlobalInterceptors(new ResponseInterceptor());
  ...
}
bootstrap();

I am a real pikachu!