3

When user navigates to a URL, which is not matched to any route, Angular router throws an error

Cannot match any routes. URL Segment: [...]

What is the correct way of handling this specific error?

When using custom ErrorHandler as specified in the ExtraOptions, this error comes as a generic Error instance, so only way to match is regexp the err.message, but that doesn't sound right.

3
  • Hi, why not adding a wild card route and then redirect with a 404 component ? Commented Sep 17, 2018 at 11:40
  • You can add a component that serves like 404 page and show some meaningful message and offer routes where to go... Or reroute directly.
    – PeS
    Commented Sep 17, 2018 at 11:41
  • I will probably do it this way, I had an idea a popup would be shown, that the route doesn't lead anywhere. Commented Sep 17, 2018 at 11:46

3 Answers 3

4

You can redirect to another route when user navigates to a url which is not matched to any route. All the undefined routes will be redirect to dashboard as per example.

Defined in routes like this ::

{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', loadChildren: './Component/dashboard/dashboard.module#DashboardModule'},
   { path: '**', redirectTo: '' }
1
  • Yes, I could redirect to a 404 page, but isn't there a way to just handle the error and display a popup or something? Commented Sep 17, 2018 at 11:44
0

you can add { path: '**', redirectTo: 'default route' }

0

Hello there is an other way to handle the error throwed by the router:

constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        // do some stuff
    }
  }
2
  • Yes, but if I am not mistaken, the problem is the same as with gobal errorhandler - I dont have a means of distinguishing the error type. Commented Sep 20, 2018 at 7:55
  • On a second thought this kind of error might be the only one Router throws. Commented Sep 20, 2018 at 7:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.