Reputation: 706
I'm trying to catch routing exceptions in my app. Basically there are 3 ways a user can navigate:
{ path: '**', redirectTo: 'errorPage'}
in the route config.router.navigate(['pageName'])
- catching that is easy too: .then(res => res, error => {
//service to log error to server
router.navigate(['errorPage']);
});
[routerLink]="somePath"
attribute.It's the third one that I don't know how to catch.
Presumably such an error could occur if the module didn't load for some reason. I need to be able to handle that (and other unforeseen events) gracefully.
TO CLARIFY
The wildcard definition works for router problems, in most cases. But here's the thing, what if there is a route defined earlier in the configuration, but it leads to a module that can't be found! (I actually had this error in develop, which is why I am aware that it can happen, we're using lazy loading, and it happened that with some network problems a required module didn't load). The router finds a route, and tries to resolve it, but can't because the module, for whatever reason, did not load. The wildcard definition doesn't help here, because the router found a path but can't reach it. So it throws an error, which I'm trying to catch. Because for some reason router errors choke the whole app.
Upvotes: 0
Views: 1223
Reputation: 2274
This { path: '**', redirectTo: 'errorPage'}
is what is called the wildcard route definition, which Angular official doc defines as:
The router will select this route if the requested URL doesn't match any paths for routes defined earlier in the configuration. This is useful for displaying a "404 - Not Found" page or redirecting to another route.
So this should work for any case when the requested route doesn't match any of the defined routes (doesn't matter if it was typed or set). Check if the routerLink definition is correct because the definition for it is without the brackets: <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
Upvotes: 0
Reputation: 455
Why not create fallback path in routing module?
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: '**', component: NotFoundComponent },
];
When user enter not existing url will be redirected to NotFoundComponent.
Upvotes: 2