This commit is contained in:
richarjiang
2026-03-15 11:35:39 +08:00
commit 6413d4f34c
27 changed files with 7589 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
import { ApiProperty } from '@nestjs/swagger';
export class ApiResponseDto<T> {
@ApiProperty({ description: '请求是否成功' })
success: boolean;
@ApiProperty({ description: '响应数据', nullable: true })
data: T | null;
@ApiProperty({ description: '错误信息', nullable: true })
message: string | null;
@ApiProperty({ description: '响应时间戳' })
timestamp: Date;
constructor(success: boolean, data: T | null, message: string | null = null) {
this.success = success;
this.data = data;
this.message = message;
this.timestamp = new Date();
}
static success<T>(data: T): ApiResponseDto<T> {
return new ApiResponseDto(true, data, null);
}
static error<T>(message: string): ApiResponseDto<T | null> {
return new ApiResponseDto<T | null>(false, null, message);
}
}

View File

@@ -0,0 +1,49 @@
import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiResponseDto } from '../dto/api-response.dto';
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(HttpExceptionFilter.name);
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let message = 'Internal server error';
if (exception instanceof HttpException) {
status = exception.getStatus();
const exceptionResponse = exception.getResponse();
if (typeof exceptionResponse === 'string') {
message = exceptionResponse;
} else if (typeof exceptionResponse === 'object') {
const responseObj = exceptionResponse as Record<string, unknown>;
message = (responseObj.message as string) || exception.message;
}
} else if (exception instanceof Error) {
message = exception.message;
this.logger.error(
`Internal error: ${exception.message}`,
exception.stack,
);
}
const errorResponse = ApiResponseDto.error(message);
response.status(status).json({
...errorResponse,
path: request.url,
});
}
}