Correct error handling for Angular 2 http result

I use the HTTP error handling strategy used in the angular.io documentation:

getHeroes () { return this.http.get(this._heroesUrl) .map(res => <Hero[]> res.json().data) .catch(this.handleError); } private handleError (error: Response) { console.error(error); return Observable.throw(error.json().error || 'Server error'); } } 

In some scenarios, instead of a JSON response, I get a status code of 204 (No data). In this case, the error handler is not called until the result is analyzed using res.json() , so the error passed to handleError is "error.json is not a function".

How can I poll the response flow to check the status code 200 (OK) or the content type of the response header "application / json" and display an error handler with a more relevant error message?

+5
source share
1 answer
 http .get('Some Url') .map(res => { // If request fails, throw an Error that will be caught if(res.statu != 200) { throw new Error('This request has failed ' + res.status); } // If everything went fine, return the response else {return res.json(); } }) 

This can help you.

This is just for understanding how to use the status from the response, you can change it according to your requirements.

The error is called only for code not 200, check this commit

+8
source

Source: https://habr.com/ru/post/1246840/


All Articles