3

How to handle navigation errors in ErrorHandler?

I tried using the following condition to check whether Error object is of NavigationError but it says false.

export class AppErrorHandler implements ErrorHandler {

  constructor() { }

  handleError(error: Error) {
if (error instanceof NavigationError) {
      //do something here, may be notify or redirect to error page.
    }
}

How to handle router navigation errors in ErrorHandler? I don't want to add wildcard routing.

Will the above condition works if the type is correct? If so, against what type I should check?

Prajwal
  • 3,930
  • 5
  • 24
  • 50

2 Answers2

3

@prajwal

try to use the next way to handle errors, it should works on 99.9% =):

import { Router, NavigationError } from '@angular/router';

 constructor( private router: Router) {
this.router.events.filter(e => e instanceof NavigationError).subscribe(e => {
  console.log(`NAV ERROR -> ${e}`);
});

}

Result:

The right relative path is ./home, but I have tried to go on ./home2

Damir Beylkhanov
  • 525
  • 3
  • 13
  • this doesn't work with `rxjs 6`. Also, where to add this? In error handler or in app component? – Prajwal Aug 20 '18 at 08:10
  • He used injecter `Router` not errors handler, maybe that is the way to go – Antoniossss Aug 20 '18 at 08:20
  • @Antoniossss But this method depends on a callback, which cannot be used in error handler. – Prajwal Aug 20 '18 at 08:31
  • @prajwal you can add this nav err event handling filter into a separate singleton service and share it on the `root` level. here you can read about it https://angular.io/guide/singleton-services – Damir Beylkhanov Aug 20 '18 at 09:39
  • why should I create a singleton service for this? – Prajwal Aug 20 '18 at 11:16
  • because such things as Error handlers, connection string managers and etc. should be created only once and they can be used by consumers globally. read articles about best practices, please. hope it would help you in your decisions – Damir Beylkhanov Aug 20 '18 at 13:51
0

The other answer was a good starting point, but did not work with Angular 13, this is what I came up with

readonly router$: Subscription;

constructor(private router: Router){

    this.router$ = this.router.events.pipe(
        filter((e) => e instanceof RouterEvent),
        filter((e) => e.constructor.name === 'NavigationError')
    ).subscribe((e: NavigationError) => {
        console.error(`Could not load URL "${e.url}" ${e.error}`);
    });
}

Don't forget to unsubscribe

ngOnDestroy() {
    this.router$?.unsubscribe();
}
CodeMonkey
  • 3,271
  • 25
  • 50