0

Hello Stack community,

Is there a efficient way of handling errors throwed inside one of following:

  • canActivate
  • canActivateChild
  • canDeactivate
  • canMatch
  • resolve
  • canLoad

While Angular navigation? Simple example would be following two routes:

    {
        path: 'path1',
        data: { enabled: true },
        canActivate: [RoutingGuardByRouteData],
        component: Path1Component
    },
    {
        path: 'path2',
        canActivate: [RoutingGuardByRouteData],
        /* note, that data object is missing here, even guard requires it */
        component: Path1Component
    },

and RoutingGuardByRouteData itself:

export class RoutingGuardByRouteData implements CanActivate {
    constructor(private router: Router) { }
    canActivate(activeRoute: ActivatedRouteSnapshot): boolean | UrlTree {
        /* This might throw error if royte data is not provided */
        const isAllowedRoute: boolean = activeRoute.data.enabled;
        if (!isAllowedRoute) {
            return this.router.parseUrl('/');
        }
        return isAllowedRoute;
    }
}

Currently, non-catched error throwed in guard will cause whole routing process to collapse. I'd love to have some good, common place to capture them in manner similar to:

function myRoutingErrorCatcher() {
  /* Extra points for finding out, from where obtain router here :) */
  this.router.parseUrl('/');
}

I'd be grateful for any ideas or suggestions

Tomas
  • 3,269
  • 3
  • 29
  • 48

1 Answers1

0

You can follow the given below point

  1. Create a new class RoutingErrorHandler that extends ErrorHandler: typescript
import { ErrorHandler, Injectable, Injector } from '@angular/core';
        import { Router } from '@angular/router';
        
        @Injectable()
        export class RoutingErrorHandler extends ErrorHandler {
          constructor(private injector: Injector) {
            super();
          }
        
          handleError(error: any) {
            if (error.name === 'NavigationCancel') {
              const router = this.injector.get(Router);
              router.navigateByUrl('/');
            } else {
              super.handleError(error);
            }
          }
        }
  1. Register the RoutingErrorHandler as a provider in your app module:
     import { NgModule, ErrorHandler } from '@angular/core';
        import { RoutingErrorHandler } from './routing-error-handler';
        
        @NgModule({
          providers: [{ provide: ErrorHandler, useClass: RoutingErrorHandler }]
        })
        export class AppModule { }
Tomas
  • 3,269
  • 3
  • 29
  • 48