Let's take a look at HttpClient first. We can handle the errors by RxJS catchError/catchError operators. The basic way to handle errors in Angular is to use Angular's HttpClient service along with RxJS operators throwError
and catchError.
The HTTP request is made, and it returns the data with a response if anything wrong happens then it returns an error object with an error status code.
Below is the service in which I used the catchAuthError() function to handle errors in Angular. This is a single service, all HTTP requests will go through this service. If any error comes up, it will handle it and show a user-friendly message to the user.
request.service.ts
There are two categories of errors which need to be handled differently:
Client-side: Network problems and front-end code errors. With HttpClient
, these errors return ErrorEvent
instances.
Server-side: AJAX errors, user errors, back-end code errors, database errors, file system errors. With HttpClient
, these errors return HTTP Error Responses.
By verifying if an error is in under error.error
, we can figure out which type of error we have and handle it accordingly.
Injecting this request.service.ts to all other services:
Now letās come to the best way to handle errors with HttpInterceptor.
It was introduced with Angular 4.3.1. It gives us the option to intercept HTTP requests and responses to transform or handle them before passing them to the server.
We can write a very clean service now, all the errors will be automatically handled by HttpInterceptor. We can even use the retry method to retry all requests before they fail.
We can modify any header, authentication token, request body, etc, before sending them to the server.
Conclusion
I hope this article helps you to understand the basic to advance ways of handling errors in Angular 12 with RxJS operators and HttpInterceptor.
Happy coding! :)