Handling errors when performing HTTP requests

Handling errors raised in our requests by inspecting the information returned in the Response object is actually quite simple. We just need to inspect the value of its Boolean property, which will return false if the HTTP status of the response falls somewhere outside of the 2xx range, clearly indicating that our request could not be accomplished successfully. We can double-check that by inspecting the status property to understand the error code or the   type   property, which can assume the following values: basiccorsdefaulterror, or opaque. Inspecting the response headers and the statusText property of the HttpResponse object will provide insightful information about the origin of the error.

All in all, we are not meant to inspect those properties on every response message we get. Angular provides an Observable operator to catch errors, injecting in its signature the HttpResponse object we require, to inspect the previous properties:

http.get('/api/bio')
.subscribe(bio => this.bio = bio)
.catch(error: Response => Observable.of(error));

Worth noting is that we capture our error by using the catch() operator and return a new operator by calling Observable.of(error) and letting our error serve as input for the new Observable we create. This is a week for us to not crash the stream, but let it live on. Of course, in a more real scenario, we would probably not just create a new Observable, but maybe log the error and return something completely different potentially or add some retry logic. The point is that with the catch() operator, we have a way of capturing the error; how you handle it depends on your scenario.

In a normal scenario, you would want to inspect more data than the error properties, aside from logging that information in a more solid exception tracking system.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset