Reputation: 3814
I am attempting to utilize Angular 2's HTTP methods in a service which is working fine until the server returns an invalid response. Here's the method code from my service:
getCalcCode(request: CalculatorRequest) {
this.http.post(this._serviceUrl, JSON.stringify(request), this.options)
.map((response: Response) => response.json().returnData as CalculatorResponse)
.catch((error) => {
return Observable.throw(error);
})
.subscribe((response: CalculatorResponse) => {
if (response.returnCode === '000') {
console.log('Code is zero!');
}
}, (error) => {
console.error('Error: : ', error);
});
}
When the server returns an invalid response, the Map
operator returns undefined, therefore, when attempting to access response.returnCode
from within my subscribe method, I receive:
ERROR TypeError: Cannot read property 'returnCode' of undefined
And the asynchronous code simply stops executing...the error function on subscribe is never called (EDIT: because the server is responding properly and the mapping is working properly, just to the wrong JSON format).
What can I do to ensure that errors within subscribe are caught from my error handler?
Thanks!
EDIT
After discussing this in the comments further, what I'm truly asking here is exactly how to catch errors from within my "subscribe" callback? Will I simply need to use a try/catch block?
Upvotes: 3
Views: 5336
Reputation: 96969
The description in comments is actually a bit inaccurate. When the source emits an error then the callback to the map()
operator is never called and the error is just send further (map()
works only with next
signals, not error
s). The "one or the other, never both" rule applies only to error
and complete
signals, not to next
signals. Of course, you can have multiple next
signals.
Then it's caught by catch()
and just rethrown.
You don't need to be using catch()
at all for this. The error is propagated as error
notification already.
The server probably doesn't send proper status codes so Angular HTTP service interprets them as next
notifications. If the server sends for example 404
or 500
status codes it'll be automatically propagated as errors and you don't need to do anything.
Upvotes: 1