Angular http request observable error does not catch error?

SebastianG picture SebastianG · Oct 11, 2018 · Viewed 8.3k times · Source

Angular 6 using HttpClient. No interceptors implemented for now.

I have an admin service where I'm doing a http call to MSGraph. In this case I'm getting an error 400 bad request which I'm sending to the notification handler.

I've slided in that console.log to make sure that the error block is firing at all and another cnosole.log to see if the 'data' getting back from the server is an error.

None of the console.logs fire yet the global error handler still displays the 400 bad request response in the console.

I'd like to be able to use this response and display a user-friendly message.

Code:

this.http.get(this.GRAPH_ROOT_URL + this.APP_ID, { headers }).subscribe(data => {
  this.notification.done(data);
  console.log(data);
}), error => {
  this.notification.error(`Error getting users from Microsoft GRAPH API. Reason: ${error}`)
  console.log("this is observable error", error);
}

Answer

Cobus Kruger picture Cobus Kruger · Oct 11, 2018

Angular 6 uses RxJS 6, which comes with a number of changes. Assuming that's what you're using, this is what I would use:

Here's what I would use:

this.http.get(this.GRAPH_ROOT_URL + this.APP_ID, { headers })
    .pipe(catchError(err => {
      this.alert.error('There was an error getting data');
      return throwError(err);
    })).subscribe(data => this.notification.done(data));

So you use pipe to call catchError, which does handle the server errors correctly.

To use catchError, you need to import it first, like this:

import { catchError } from 'rxjs/operators';