How to handle Server and Client errors in Angular Universal (SSR)
The problem
One of the main issues that arose when trying Angular Universal for one of my personal projects, was the inability to properly log the errors that were generated in the server.
For the client-side of part of the app, you might take some different route than the server-side one. For example, redirect to different parts of the site or show different messages, and even if there’s been an error on the server that you don’t want the user to make aware of, just log it.
The solution
So here is were angular platform id and isPlatformServer method come into play and we can use those to take different paths on error handling for each side of our app.
First of all, we need to have an error handler, where we handle all of the errors that were not explicitly cached on our app that implements Angular’s core ErrorHandler interface:
Now we need to tell Angular to use the handler adding the provider into the app module:
Now on the handler, we can specify which actions to take on each side of our application:
That’s all folks! If got here, you might be interested in some of my other articles: