feat: 统一后端响应格式

This commit is contained in:
2025-12-15 22:24:32 +08:00
parent e30fe60277
commit 6157976029
4 changed files with 70 additions and 6 deletions

View File

@@ -0,0 +1,22 @@
import { HttpStatus } from '@nestjs/common';
export class BusinessException {
public statusCode: HttpStatus;
public message: string;
public code: number;
public data: any;
constructor(args: {
statusCode?: HttpStatus,
message?: string,
code?: number,
data?: any,
}) {
const { statusCode, message, code, data } = args;
this.statusCode = statusCode || HttpStatus.BAD_REQUEST;
this.message = message || '请求错误';
this.code = code || -1;
this.data = data || null;
}
}

View File

@@ -0,0 +1,43 @@
import { ArgumentsHost, ExceptionFilter, HttpException, HttpStatus, Logger } from "@nestjs/common";
import { Request, Response } from "express";
import { BusinessException } from "../exceptions/business.exception";
export class GlobalExceptionsFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = {
success: false,
message: '服务器内部错误',
code: -1,
data: null as any,
};
if (exception instanceof BusinessException) {
statusCode = exception.statusCode;
const { message, code, data } = exception;
errorResponse = {
...errorResponse,
message, code, data,
}
} else if (exception instanceof HttpException) {
// 当HttpException传入类型为string时响应data为nullmessage为传入的string
// 其他请况object/number响应为传入数据message为HttpException的错误码
statusCode = exception.getStatus();
const response = exception.getResponse() as Record<string, any>;
if (response.message) {
errorResponse.message = response.message;
} else {
errorResponse.message = '请求失败';
errorResponse.data = response;
}
} else {
Logger.warn(exception, request.path);
}
response.status(statusCode).json(errorResponse);
}
}

View File

@@ -15,7 +15,8 @@ export class ResponseInterceptor implements NestInterceptor {
): Observable<any> | Promise<Observable<any>> { ): Observable<any> | Promise<Observable<any>> {
return next.handle().pipe( return next.handle().pipe(
map((data) => ({ map((data) => ({
statusCode: 200, success: true,
code: 0,
message: '请求成功', message: '请求成功',
data, data,
})), })),

View File

@@ -2,6 +2,7 @@ import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { BadRequestException, ValidationPipe } from '@nestjs/common'; import { BadRequestException, ValidationPipe } from '@nestjs/common';
import { ResponseInterceptor } from './common/interceptors/response.interceptor'; import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { GlobalExceptionsFilter } from './common/filters/global.exceptions.filter';
async function bootstrap() { async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
@@ -18,15 +19,12 @@ async function bootstrap() {
? Object.values(error.constraints)[0] ? Object.values(error.constraints)[0]
: '验证失败'; : '验证失败';
throw new BadRequestException({ throw new BadRequestException(firstConstraint);
message: firstConstraint,
error: 'Bad Request',
statusCode: 400,
});
}, },
}), }),
); );
app.useGlobalInterceptors(new ResponseInterceptor()); app.useGlobalInterceptors(new ResponseInterceptor());
app.useGlobalFilters(new GlobalExceptionsFilter());
await app.listen(process.env.PORT ?? 3001); await app.listen(process.env.PORT ?? 3001);
} }
bootstrap(); bootstrap();