In my Angular 2 app, I have a Service with an http.get
method that returns an Observable.
campaign.service.ts
public getCampaign(campaignId: string): Observable<Campaign> {
return this.http.get(this.campaignsUrl + '/' + campaignId, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || body || {};
}
private handleError(error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
I then call it in my Component, like so:
campaign.component.ts
this.campaignService.getCampaign(paramId)
.subscribe(
obj => {
// do something
},
() => {
// handle error here
}
});
However, if the http.get
call returns a HTTP 500, I never hit my .catch(...)
section in my Service class. Console outputs an uncaught exception.
GET http://localhost:9001/api/v1/campaigns/4175edc4 500 (Internal Server Error)
EXCEPTION: Response with status: 500 Internal Server Error for URL: http://localhost:9001/api/v1/campaigns/4175edc4
Uncaught Response {_body: "{"message":"invalid input syntax for uuid: \"4175edc4\""}", status: 500, ok: false, statusText: "Internal Server Error", headers: Headers…}
What could I be doing wrong here?
Angular 2 follows the Fetch spec, which only throws errors when there was a problem with the request operation. It does not throw if an error response was returned (as an error response is still a valid response).
You need to check the response.ok
attribute to ensure it is not 404 or 500 etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With