|
@@ -4,16 +4,21 @@ import {
|
|
|
ArgumentsHost,
|
|
ArgumentsHost,
|
|
|
HttpException,
|
|
HttpException,
|
|
|
HttpStatus,
|
|
HttpStatus,
|
|
|
|
|
+ Logger,
|
|
|
} from '@nestjs/common';
|
|
} from '@nestjs/common';
|
|
|
import { ErrorResponse } from '../error/error.response';
|
|
import { ErrorResponse } from '../error/error.response';
|
|
|
|
|
+import * as process from 'node:process';
|
|
|
|
|
|
|
|
@Catch()
|
|
@Catch()
|
|
|
export class GlobalExceptionFilter implements ExceptionFilter {
|
|
export class GlobalExceptionFilter implements ExceptionFilter {
|
|
|
|
|
+ private readonly logger = new Logger(GlobalExceptionFilter.name); // 使用 Logger
|
|
|
|
|
+
|
|
|
catch(exception: any, host: ArgumentsHost) {
|
|
catch(exception: any, host: ArgumentsHost) {
|
|
|
const ctx = host.switchToHttp();
|
|
const ctx = host.switchToHttp();
|
|
|
const response = ctx.getResponse();
|
|
const response = ctx.getResponse();
|
|
|
|
|
|
|
|
const { status, errorResponse } = this.formatException(exception);
|
|
const { status, errorResponse } = this.formatException(exception);
|
|
|
|
|
+ this.logError(exception);
|
|
|
|
|
|
|
|
response.status(status).json(errorResponse);
|
|
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}`);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
}
|
|
}
|