【问题标题】:Reading the response in case of exception in Exception Filter在异常过滤器中读取异常情况下的响应
【发布时间】:2020-07-14 20:50:12
【问题描述】:

这是整体场景。

  1. 我们在模块级别应用了异常过滤器。
  2. 我们必须为某些数据调用一些第 3 方 REST。
  3. 对 3rd 方的其余调用失败并显示 400 并且有一些响应数据。
  4. 我们必须将此返回给调用者。

所以,以一种非常简单的方式,有 3 个部分:

  1. A 正在呼叫 B
  2. B 正在调用 C,而 C 没有像 https://run.mocky.io/v3/a3b8da60-f2a4-4658-a601-e044a151fc7b 这样的响应正文

所以,如果我们查看响应,它类似于:

------------ (X) --------------
HTTP RESPONSE STATUS: 400
RESPONSE BODY:
{
  status: 400,
  code: 'BAD_REQUEST',
  message: 'Message'
}

我需要阅读此响应正文并将其发送回 A。

这里有详细的解释。

app.module.ts

@Module({
 .....
 providers: [
    ConvertErrorStatusToCode,
    {
      provide: 'APP_FILTER',
      useClass: HttpExceptionFilter,
    }
 ],
})
export class AppModule implements NestModule{}

product.module.ts

@Module({
  controllers: [<Controllers>],
  providers: [ProductService],
  imports: [HttpModule]
})
export class ProductModule {}

product.service.ts

 @Injectable({ scope: Scope.REQUEST })
 export class ProductService {
      constructor(<HTTPSERVICE INJECTED>) {}
      async somethirdpartycall(): Promise<Partial<MyDto>> {
         // here using httpservice i call the URL pasted and 
      }
 }

http-exception.filter.ts

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
      
      catch(exception: any, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const request: Request = ctx.getRequest<Request>();
        const response: Response = ctx.getResponse<Response>();
        // how to read the response of the request that failed
        // at (X)
      }
}

我正在尝试获取 RESPONSE BODY 但无法这样做。所以:

  1. 如何在异常过滤器中读取响应正文
  2. 这是一种好的方法吗,还是我们应该采用其他方法

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    我建议查看官方文档中的拦截器

    https://docs.nestjs.com/interceptors#exception-mapping

    尤其是Exception mapping,这似乎是一个很好的案例(转换错误消息)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-01
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多