I have this simple global error handler which stems from angular ErrorHandler
. now regardless the location of the error, the initial handling is done twice, or at least this what it seems. my console logs the same error twice for the first time and as singles after that if the error persists, any reason why?
import { ErrorHandler, Injectable, Injector } from "@angular/core";
import { Router } from '@angular/router';
@Injectable()
export class ArtCoreErrorHandler implements ErrorHandler {
constructor(private injector: Injector) { }
handleError(error) {
console.log(error)
const message = error.message ? error.message : error.toString();
if (message == 'JWT must have 3 parts') {
router.navigate(['/']).then(
() => alert('wrong'),
);
location.reload();
}
throw error;
}
}
and in my app module
providers: [
{provide: ErrorHandler, useClass: ArtCoreErrorHandler},
MDBSpinningPreloader,
.........]
One traditional way of handling errors in Angular is to provide an ErrorHandler class. This class can be extended to create your own global error handler. This is also a useful way to handle all errors that occur, but is mostly useful for tracking error logs.
The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError and catchError. The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.
Global Error HandlerThis method is called whenever an error is thrown somewhere in the application. The error is passed as a parameter and can be processed further inside the method. In our case a dialog is opened where the error message should be displayed and the error is logged to the browser console.
Global Error Handling in Angular is handled by the Errorhandler class which is part of the @angular/core module. This is a global error handler class which catches all exceptions thrown by the application. In this approach, we create a class that will be implemented by the ErrorHandler class.
If your error is being thrown because of an Observable failing, like say a failed HTTP request via HttpClient, it could be that you are subscribing to the observable twice. Multiple subscriptions will cause multiple errors, even if the source observable is only throwing the error once.
In this example:
let obs = this._http.get('https://i-do-not-exist.test').pipe(share());
obs.subscribe(() => {})
obs.subscribe(() => {})
The HTTP request will only run once, but 2 errors will be thrown and caught by the global error handler.
See this StackBlitz
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