Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 How to display error page while keeping route

Apologies if this is somewhere else, but my normal searching tactics have failed me.

I'd like to display a custom error page when I receive a 500 from the API. I'm using restangular and have a response interceptor that redirects to the error page when I receive the 500, using:

this.router.navigate(['/error']);

This all works. However, I'd like to keep the previous URL in the browser navigation bar so that when the user refreshes it tries the previous page again, whereas right now they have to re-navigate to the broken page to try again.

Thanks!

like image 711
Robin Schaaf Avatar asked May 19 '17 16:05

Robin Schaaf


People also ask

How to show 404 page in Angular?

To set up a 404 page in the angular routing, we have to first create a component to display whenever a 404 error occurred. In the following approach, we will create a simple angular component called PagenotfoundComponent. Creating Component: Run the below command to create pagenotfound component.

How to catch error in Angular component?

One traditional way of handling errors in Angular is to provide an ErrorHandler class. This class can be extended to create your own global error handler. This is also a useful way to handle all errors that occur, but is mostly useful for tracking error logs.

How to redirect in Angular component?

To set up a redirect, configure a route with the path you want to redirect from, the component you want to redirect to, and a pathMatch value that tells the router how to match the URL.


1 Answers

You can add this:

setRouteErrorHandler(): void {
    let errorRoute = null;

    this.router.errorHandler = (error): void => {
        this.location.go(errorRoute.url);
        this.router.navigate(['/error'], { skipLocationChange: true, replaceUrl: true });
    };

    this.router.events
        .filter((next) => next instanceOf NavigationError)
        .subscribe((next) => {
            errorRoute = next;
    });
}

and call setRouteErrorHandler() from AppModule constructor or implement your own APP_INITIALIZER

like image 148
Tzach Ovadia Avatar answered Nov 15 '22 06:11

Tzach Ovadia