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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With