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>> {
return next.handle().pipe(
map((data) => ({
statusCode: 200,
success: true,
code: 0,
message: '请求成功',
data,
})),