首页 > 解决方案 > NestJS:全局错误处理程序未捕获未处理的承诺拒绝

问题描述

我正在使用 NestJS,我有一个控制器,它从抛出异常的服务中调用异步方法,如下所示:

@Get('gde/expedientes/:expediente/caratula')
  async readExpedientesCaratulaFromGDE(@Param('expediente') expediente: string): Promise<readCaratulaResultType> {
    return await this.client.readExpedienteCaratula(expediente)  // this throws an Exception!
  }

该服务只是抛出常规 JavaScript 错误,而不是 NestJs HttpExceptions。

我希望全局处理程序能够捕获它,但 http 客户端只是挂起,我在服务器中收到以下错误:

problem with request: getaddrinfo ENOTFOUND xxx.xxx.xxx
(node:17518) UnhandledPromiseRejectionWarning: TypeError: exception.getStatus is not a function
    at GDEExceptionFilter.catch (/home/sas/devel/apps/trabajo-it/coordinacion/gestion-documental/tramites-consulta/src/api/dist/gde/gde-exception.filter.js:16:34)
    at ExceptionsHandler.invokeCustomFilters (/home/sas/devel/apps/trabajo-it/coordinacion/gestion-documental/tramites-consulta/src/api/node_modules/@nestjs/core/exceptions/exceptions-handler.js:33:26)
    at ExceptionsHandler.next (/home/sas/devel/apps/trabajo-it/coordinacion/gestion-documental/tramites-consulta/src/api/node_modules/@nestjs/core/exceptions/exceptions-handler.js:13:18)
    at /home/sas/devel/apps/trabajo-it/coordinacion/gestion-documental/tramites-consulta/src/api/node_modules/@nestjs/core/router/router-proxy.js:13:35
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
(node:17518) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:17518) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我确实是throwing inside of an async function without a catch block,但我期待它由 Nest 处理。我想开发自己的全局处理程序并捕获“请求问题:getaddrinfo ENOTFOUND xxx.xxx.xxx”错误。

有什么办法可以捕捉到它,还是我应该总是将我的控制器方法包含在一个try / catch块中???

标签: javascripterror-handlingpromisenestjs

解决方案


推荐阅读