fix: 增加错误打印
This commit is contained in:
1 parent
fce8ada51e
commit
e0cf2c00d6
1 file changed
+15
@@ -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}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user