【问题标题】:How to catch 3rd party api error response using NestJS' httpService?如何使用 NestJS 的 httpService 捕获 3rd 方 api 错误响应?
【发布时间】:2022-05-07 01:23:45
【问题描述】:

假设我像这样使用 httpService 发出请求

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

假设 example.com/data api 发送类似“Cannot send data without specified user id”之类的消息。关于这个请求(如果我通过 curl 提出这个请求)

现在,如果我在上面的代码块中使用 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)"

但是如果我这样写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();
      });

我会在我的日志中得到第 3 方 api 响应“如果没有指定用户 ID,就无法发送数据。”

那么,有没有办法让 httpService 默认以这种方式运行?比如拦截器什么的?

【问题讨论】:

    标签: javascript http nestjs


    【解决方案1】:

    你可以这样试试:

    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);
          })
        )
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2018-01-02
    • 2020-12-19
    • 2020-08-10
    • 2019-08-31
    • 2021-07-28
    • 2019-08-21
    • 2016-10-29
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多