SmallhillCZ
SmallhillCZ

Reputation: 171

How to handle "Cannot match any routes" error?

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.

Upvotes: 3

Views: 1295

Answers (3)

Arigui Ahmed
Arigui Ahmed

Reputation: 422

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
    }
  }

Upvotes: 0

Bhavya Sanchaniya
Bhavya Sanchaniya

Reputation: 563

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: '' }

Upvotes: 4

sabrine abdelkebir
sabrine abdelkebir

Reputation: 83

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

Upvotes: 0

Related Questions