diff --git a/src/core/exception/global-exception.filter.ts b/src/core/exception/global-exception.filter.ts index 21b697c..aeee41d 100644 --- a/src/core/exception/global-exception.filter.ts +++ b/src/core/exception/global-exception.filter.ts @@ -4,16 +4,21 @@ import { ArgumentsHost, HttpException, HttpStatus, + Logger, } from '@nestjs/common'; import { ErrorResponse } from '../error/error.response'; +import * as process from 'node:process'; @Catch() export class GlobalExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(GlobalExceptionFilter.name); // 使用 Logger + catch(exception: any, host: ArgumentsHost) { const ctx = host.switchToHttp(); const response = ctx.getResponse(); const { status, errorResponse } = this.formatException(exception); + this.logError(exception); response.status(status).json(errorResponse); } @@ -68,4 +73,14 @@ export class GlobalExceptionFilter implements ExceptionFilter { }, }; } + + private logError(exception: any): void { + // 记录错误信息 + this.logger.error(`Error: ${exception.message}`); + + // 仅在开发或测试环境中打印堆栈跟踪 + if (['development', 'test'].includes(process.env.NODE_ENV)) { + this.logger.error(`Stack Trace: ${exception.stack}`); + } + } }