Angular Rxjs Error Handling flow

In Angular 2+, http are all RX based. so the error flow is quite different from what we used to have in angular 1.x’s promise based way.

consider the code

this.http.get(‘someurl’)
.map((res: Response) => {
return res.json();
})
.catch((err) => {
console.log(error);
Observable.throw(‘my custom err msg’);
})
.subscribe((res)=>{
console.log(res);
}, (err) => {
console.log(err);
}, ()=> {
console.log(‘complete’);
})

So the basic flow is if anything exception happened, the error handler function in the catch block will be called first. That function should return an Observable since it is a chain. Then the (err) function will be invoked. In the context of an HTTP request in Angular2, a response with a status code different than 2xx is considered as an error.

Note, if we do not use Observable.throw() in catch but return some random result, it would probably result in funky result. In the ​subscribeToResult function, there are multiple type checks. For example, if we return an array, if would be treated valid and be passed to the first handler rather than the error handler. If we return a random object like the error object, we will get TypeError: unknown type returned, error and trigger the 2nd handler(error handler).

Another note is if angular will return some odd error object with status: 0 when invoking some non-exist cross origin endpoints. This is because Whenever you make an api call to a non existing route, the browser sends a preflight request (a) . If the backends error handle strategy is to return an http response with 404 code and the error details in the body, the browser returns a generic error with http status code 0 without the actual server’s payload. The second call is never made because there is no sense in doing it since the preflight went wrong. In the end the error thrown have 0 status without any information about the real cause of the error.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s