5

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?

3
  • Thanks, I missed that one. For anyone else coming to this, please note that the error handling behavior since alpha 47 applies only to status codes below 200 and above 299. Since my status code is 204 (Not Found), I still need to manually throw the error as given in the "alpha 46 and below". Commented Apr 11, 2016 at 12:33
  • Er, HTTP response 204 is "no data" ("not found" is 404). Commented Apr 11, 2016 at 13:41
  • Yes, sorry I meant "No Data". Commented Apr 11, 2016 at 18:39

1 Answer 1

9
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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.