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

Suppose i make a request using httpService like this

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." on this request (if i make this request via curl)

Now, if i use httpService like in the codeblock above i get this ambiguous message:

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(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."

So, is there a way to make the httpService behave this way by default? like an interceptor or something?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manuel de la Torre