【发布时间】:2020-07-14 20:50:12
【问题描述】:
这是整体场景。
- 我们在模块级别应用了异常过滤器。
- 我们必须为某些数据调用一些第 3 方 REST。
- 对 3rd 方的其余调用失败并显示 400 并且有一些响应数据。
- 我们必须将此返回给调用者。
所以,以一种非常简单的方式,有 3 个部分:
- A 正在呼叫 B
- 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 但无法这样做。所以:
- 如何在异常过滤器中读取响应正文
- 这是一种好的方法吗,还是我们应该采用其他方法
【问题讨论】:
标签: nestjs