Handling HTTP Error Messages Globally using Interceptors and Toasters [Angular]
Handle all HTTP error messages in your whole Angular app using Interceptors and NGX-Toaster.
What are Interceptors?
According to Angular official docs, Interceptors are .ts files that Intercept and handle HTTP Request or HTTP Response.
In other words, every single HTTP request or response will be passed through an interceptor, that way we can listen to HTTP failure response in order to handle the error in the UI based on the status code of the response.
Creating an Interceptor.
An interceptor is a service that implements HttpInterceptor interface, So we will need the @Injectable( ) decorator and intercept( ) method as the following:
The intercept method takes 2 arguments, req, and next
req: The outgoing request object to handle.
next: The next interceptor in the chain, or the backend if no interceptors remain in the chain.
and it returns an Observable.
And in the app.module.ts
Import HTTP_INTERCEPTORS from @angular/common/http and add an object to the providers’ array like the following:
Subscribing to HTTP requests.
Now inside the returned Observable let’s create the logic to handle the errors
We will pass the req to next.handle( ) method and subscribe to it.
In the success case, we will just call the next(res) to complete the cycle of the HTTP response.
And for the failure case, We will handle the HTTP error message, Right now we will just console.error(err).
Creating HandleErrorService.
Instead of consoling the whole error directly inside the Interceptor, let’s create a service to do so as the following:
In the handleError method, we take an HttpErrorResponse as an argument and separate the client-side and the backend errors.
For now, we will just console a generic message for the backend error “Something Went Wrong”
Installing ngx-toastr.
npm i ngx-toastr
Now in HandleErrorService.ts import ToasterService from ‘ngx-toastr’ and substitute console.error with toaster.error
And in app.module.ts
Import ToastrModule and BrowserAnimationsModule and you can change the options of the toaster like the following:
For my code, I made the toaster to appear from the left bottom and it will take 10sec until it disappears. (Learn More About Toasters)
Now back to out Interceptor Import the created HandleErrorService and substitute the console.error with the HandleErrorService method:
Now in every single HTTP failure, the Interceptor will handle it and display the messages via Toasters.
So far and so good!
We can take the handleError method to the next level and display the backend error message accordingly to the status code instead of the generic “Something Went Wrong” message.
I will check for the most common backend failure cases: