JSON
JSON

Reputation: 1623

Why my global error handler get invoked twice in my Angular app?

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,
.........]

Upvotes: 7

Views: 2265

Answers (1)

christiaan
christiaan

Reputation: 378

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

Upvotes: 6

Related Questions