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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With