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

zy1mlcev  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(431)

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

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

假设example.com/data api在此请求上发送一条消息,如“在未指定用户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();
      });

我将在我的日志中得到第三方api响应“无法在未指定用户id的情况下发送数据”
那么,有没有办法让httpservice在默认情况下以这种方式运行?像拦截器什么的?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题