Proper error handling for Angular 2 http result
14,373
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 may help you.
This is just for understanding how to use the status from the response, you can modify according to your requirement.
Error is thrown only for non 200 code check this commit
Author by
gxclarke
Updated on June 12, 2022Comments
-
gxclarke almost 2 years
I've been using 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 will receive a 204 status code (No Data). In this case, the error handler doesn't get invoked until failing to parse the result via
res.json()
, so the error passed to handleError is "error.json is not a function".How can I interrogate the response stream to check for a 200 (OK) status code or a response header content-type of "application/json", and signal an error handler with a more relevant error message?