简体   繁体   English

如何使用 NestJS 的 httpService 捕获第三方 api 错误响应?

[英]How to catch 3rd party api error response using NestJS' httpService?

Suppose i make a request using httpService like this假设我像这样使用 httpService 发出请求

const response = await this.httpService
      .request({
        url: 'https://example.com/data',
        method: 'POST',
      })
      .toPromise()
      .catch(error => console.log(error))

Assume that example.com/data api sends a message like "Cannot send data without specifying user id."假设 example.com/data api 发送了类似“无法在不指定用户 ID 的情况下发送数据”的消息。 on this request (if i make this request via curl)根据这个请求(如果我通过 curl 发出这个请求)

Now, if i use httpService like in the codeblock above i get this ambiguous message:现在,如果我像上面的代码块一样使用 httpService,我会收到这条不明确的消息:

Error: Request failed with status code 400 at createError (/workspace/node_modules/axios/lib/core/createError.js:16:15) at settle (/workspace/node_modules/axios/lib/core/settle.js:17:12) at IncomingMessage.handleStreamEnd (/workspace/node_modules/axios/lib/adapters/http.js:236:11) at IncomingMessage.emit (events.js:203:15) at endReadableNT (_stream_readable.js:1145:12) at process._tickCallback (internal/process/next_tick.js:63:19)"

but if i write the catch statement like this但是如果我这样写 catch 语句

.catch(error => {
        const errorLog = _.pick(error.response, [
          'status',
          'statusText',
          'data',
        ]);
        this.logger.error(
          util.inspect(
            {
              ...errorLog,
              user: { id: user.id },
            },
            { showHidden: false, depth: null },
          ),
        );

        throw new InternalServerErrorException();
      });

I'll get the 3rd party api response in my logs "Cannot send data without specifying user id."我将在我的日志中收到第 3 方 api 响应“无法在不指定用户 ID 的情况下发送数据。”

So, is there a way to make the httpService behave this way by default?那么,有没有办法让 httpService 默认以这种方式运行? like an interceptor or something?像拦截器之类的?

You can try like this:你可以这样尝试:

const response = await this.httpService
  .request({
    url: 'https://example.com/data',
    method: 'POST',
  }).pipe(
      catchError((e) => {
        throw new HttpException(e.response.data, e.response.status);
      })
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM