I have an application with an globalError handler like this:
import { Injectable, ErrorHandler, Injector } from "@angular/core";
import { Router } from "@angular/router";
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(
private injector: Injector) { }
public handleError(error: any) {
console.error("Something went wrong");
//.. Handle error here
}
}
This always worked in every constallation. If an error was thrown the global handler caught it and handled it.
Now after upgrading to RxJs 6.2.2 I understood that catching http errors changed.
Code errors still keep working but errors thrown by the HttpClient are not globally caught. The GlobalErrorHandler is not fired any more.
I am aware that I can handle errors within my service and that works fine like this:
doSomething() {
return this.http
.get("http://someURL").pipe(
map((res: any) => { console.log(res) }),
catchError(this.handleError<any>(`blabla`))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
console.log("Now throwing error");
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
// ToDo: Global Error handler hier aufrufen....
return of(result as T);
};
}
But I actually would like to handle all errors centrally.
What is the correct way with Angular 6 and RxJs 6 to handle errors centrally?
hmm did you try it? In my current Angular 6 application, the global ErrorHandler is called, when nobody else catches the bad HTTP result. Then the event goes through the whole stream, runs into the subscribe callback, doesn´t find a error function and then move directly into the global error handling.
So for me it worked fine. (Angular 6.0.9, RXJS 6.2.1)
I personaly really like to use the specific rxjs error catching most of the time. It allows for specific responses. For some HTTP Errors i want to try a retry, for some it´s okay to work with default values, and for some i have to raise the red flag and let the application die a beautiful death.
The best is, you can catch the error very near to the call, handle it (like do a retry or return a default) and the subscribers want even realize that there was an error handling active.
I´m using the global ErrorHandler and it´s catchAll logic mostly only as last wall of defence.
warm regards
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