Prajwal
Prajwal

Reputation: 4000

Angular routing exceptions handing in error handler

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?

Upvotes: 3

Views: 7771

Answers (2)

CodeMonkey
CodeMonkey

Reputation: 3331

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();
}

Upvotes: 0

Damir Beylkhanov
Damir Beylkhanov

Reputation: 545

@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

Upvotes: 3

Related Questions