在我们的NestJS-app中,我们设置了一个自定义的错误过滤器,用于捕获特定类型的错误。对于这些错误,我们需要向elasticsearch发出请求,以便记录相应的错误信息。因为elasticsearch请求是异步的,所以我定义了catch方法async
@Catch(MyExceptionType)
@Injectable()
export class MyExceptionFilter implements ExceptionFilter {
constructor(private readonly elasticsearchService: ElasticsearchService) { }
async catch(exception: MyExceptionType, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const request = ctx.getRequest<MyRequestModel>();
const response = ctx.getResponse<MyResponseModel>();
const elasticSearchPayload = PayloadBuilder.of(request, exception);
await this.elasticsearchService.report(elasticSearchPayload);
// ...
response.status(exception.getStatus()).json({...});
}
}现在-到目前为止,这一切都很好,但我想知道这是否真的可以这样做,因为ExceptionFilter接口严格地将catch声明为同步方法。
我们这样做会遇到麻烦吗?
发布于 2020-09-10 01:06:24
ExceptionFilters是用来定义错误处理逻辑的。我不认为让它异步应该是一个问题,Nest只是不会等待逻辑完成,但是,由于它的自定义筛选器代码的编写方式,它不应该调用任何其他异常处理程序。
https://stackoverflow.com/questions/63812764
复制相似问题