Search code examples
angularurlangular-routingangular-router

Handle URL parse errors in Angular 5 router


I'm rewriting an AngularJS 1.5 application in Angular 5. The application supports complex searching where all parameters that affect the search result are contained in the URL / route path. Users can bookmark search URLs to re-apply the same search criteria.

The 1.5 app's ui-router configuration separates route path parameters with / and several of these parameters are objects, so the configured format is /{parameter1:json}/:parameter2/{parameter3:json}/. Angular 5 doesn't support this same approach. I have to use a single JSON-encoded object for all parameters with the format /:parameters.

I'm implementing a legacy support route that recognises when a user attempts to visit a legacy (1.5) search URL and instead directs the user to the new (5) URL with the same parameters applied. In most scenarios this works fine.

However the legacy application does not properly URL-encode some of its parameters. This hasn't presented any issues in 1.5 ui-router but the Angular 5 router errors with ERROR Error: Cannot parse url '/... and the application fails with blank content - it doesn't redirect anywhere.

The un-encoded URL parameters are already 'in the wild' so I need to handle the scenario where URLs cannot be parsed. Unfortunately the documentation doesn't seem to offer any way to handle errors in URL parsing.

EDIT: Providing an errorHandler in the config object for RouterModule.forRoot doesn't catch the error. Adding a global ErrorHandler class to the app isn't helpful because the error object doesn't tell me if it's a routing error or some other kind of error.

Is there any way that I can catch URL parsing errors, or provide a fallback behaviour for error scenarios?


Solution

  • you can use UrlSerializer, to change url behavior, here is an example of deleting parenthesis from urls

     import { UrlTree ,DefaultUrlSerializer, UrlSerializer } from '@angular/router';
    
    export class cleanUrlSerializer extends DefaultUrlSerializer {  
    public parse(url: string): UrlTree {
     function cleanUrl(url) {
        return url.replace(/\(|\)/g,'') // for example to delete parenthesis
     }
     return super.parse(cleanUrl(url));
    }
    }
    

    import this class and add it as provider in your module

    providers: [
    {
        provide: UrlSerializer,
        useClass: cleanUrlSerializer 
    }
    ]