Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rethrow errors of HttpService call with NestJS?

I am using NestJS to essentially proxy a request to another api using the HttpService (an observable wrapped Axios library). For example:

return this.httpService.post(...)
  .pipe(
    map(response => response.data),
  );

This works properly when the call is successful; however, if there's an error (4xx), how do I properly return the status and error message?

I've figured out how to do it with promises, but if possible I would like to stay within an observable.

like image 210
Chaz Avatar asked Apr 09 '19 21:04

Chaz


1 Answers

You can use catchError to rethrow the exception with the corresponding status code:

import { catchError } from 'rxjs/operators';

this.httpService.get(url)
      .pipe(
        catchError(e => {
          throw new HttpException(e.response.data, e.response.status);
        }),
      );

Note that error.response might be null, see the axios docs for all error cases to check for.

Also, axios does not throw for 4xx errors as they might be expected and valid responses from the API. You can customize this behavior by setting validateStatus, see docs.

like image 75
Kim Kern Avatar answered Oct 11 '22 20:10

Kim Kern