From e0cf2c00d668ab09cd6d6ed325d80866931950e4 Mon Sep 17 00:00:00 2001 From: IlhamTahir Date: Sun, 19 Jan 2025 20:26:51 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=A2=9E=E5=8A=A0=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/core/exception/global-exception.filter.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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}`); + } + } }