Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
Whenever you do an HTTP request, there are things that could go wrong. If things go wrong the request will return a response with an error code. Based on this error code you for example want to inform the user what went wrong. now, would it be handy if you can put this logic in one place and reuse it everywhere? Read on!
Photo by Duffy Brook on Unsplash
You can only deal with http errors if you attach a catch to your request. This can possibly look like this:
When your application grows, the amount of HTTP requests increases as well. Attaching a catch to every request is not exactly DRY. As of Angular 4.3, where a new HttpModule is introduced, we can finally use the traditional interceptor again.
Using an http Interceptor
When using an http interceptor the basic idea is that all the requests that are made within your module are routed trough this interceptor. This means you can automatically add or remove properties to each request. This can be handy when you’re talking to a protected API and need to send an api-key with each request.
Since every request you’re making goes trough this interceptor, we can also use this interceptor to catch all requests that return as an instance of HttpErrorResponse. This is how you do that:
We send the request to the HttpHandler and then execute the request. In the callback function we check for errors. If the error is an instance of HttpErrorResponse we can send the request to an error handler that displays a nice little message with what went wrong.
In the stackblitz below, you can see a fully working example.
What this does not catch
As mentioned several times before this way of intercepting will only catch http response with an instance of HttpErrorResponse . This means that if you for example create a map on your request to format your response and make an error in there, this will not catch it.
Conclusion
Using this interceptor setup is especially useful when you’re application relies a lot on interaction with an external rest API. If the API is properly setup it will return a nice error message when a request was incorrect. This message can now easily be displayed and showed to the user. If you do a lot of client-side formatting on your Http requests you should still create logic for handling potential errors there.
Global HTTP error catching in Angular 4.3+ was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.