全局异常过滤器未捕获某些错误
我最近创建了一个全局异常过滤器,但我刚刚注意到,它没有捕获一些错误,例如:
TypeError: Cannot read properties of undefined (reading 'dataNumber')
我的过滤器:
@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
constructor(
private readonly httpAdapterHost: HttpAdapterHost,
private readonly logger: LoggerService,
) {}
catch(exception: Error, host: ArgumentsHost): void {
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const httpStatus =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const responseBody = {
statusCode: httpStatus,
path: httpAdapter.getRequestUrl(ctx.getRequest()),
cause: `${exception.name}: ${exception.message}`,
timestamp: new Date().toISOString(),
};
this.logger.error(responseBody?.cause);
httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
}
我将它用作我的 App.module
:
{
provide: APP_FILTER,
useClass: GlobalExceptionsFilter,
},
目前,我还有一个 SCPModule
正在同一个 App.module
上导入,该错误发生在 SCPModule 内的 SCPService 上...每个模块都这样吗?需要使用我的过滤器作为提供者?
I've recently created a Global exception filter, but I just noticed that, some errors are not being caught by it, like:
TypeError: Cannot read properties of undefined (reading 'dataNumber')
My filter:
@Catch()
export class GlobalExceptionsFilter implements ExceptionFilter {
constructor(
private readonly httpAdapterHost: HttpAdapterHost,
private readonly logger: LoggerService,
) {}
catch(exception: Error, host: ArgumentsHost): void {
const { httpAdapter } = this.httpAdapterHost;
const ctx = host.switchToHttp();
const httpStatus =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const responseBody = {
statusCode: httpStatus,
path: httpAdapter.getRequestUrl(ctx.getRequest()),
cause: `${exception.name}: ${exception.message}`,
timestamp: new Date().toISOString(),
};
this.logger.error(responseBody?.cause);
httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
}
And I'm using it as a provider on my App.module
:
{
provide: APP_FILTER,
useClass: GlobalExceptionsFilter,
},
Currently, I also have a SCPModule
which is being imported on the same App.module
, that error is happening on the SCPService inside the SCPModule... Does every module needs to use my filter as a provider?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论