Reputation: 33
I am communicating with a webservice and the return can be negative or porisitvo and will fall into the success of the call, but if the return is negative I need to manually throw an exception
.map(res => res.json())
.subscribe(res => {
let returno = JSON.parse(res.d);
if (returno.status == 'success') {
this._loggedIn(returno);
} else {
throw returno;
}
}, err => {
console.error('ERROR', err);
});
Upvotes: 2
Views: 1744
Reputation: 6252
I expect you'll want all of your subscribers to handle the error in the same way? Therefore, you can handle the error at the Observable level, not the Subscriber level.
Thus, you can do something like the following:
public tryLogin(url: string): Observable<any> {
return this.http.get(url)
.map(res => res.json().d)
.map(res => {
if (res.status !== 'success') {
Observable.throw(res);
}
return res;
});
}
Then you can call this code in the following fashion:
this.tryLogin('mydata')
.subscribe(
data => this._loggedIn(data),
err => console.log(err);
)
The great thing with this approach is, if you don't want your subscribers to know what's gone on, you can abstract that and either authenticate them in the next
callback, or handle the event of a failure in the error
callback.
Upvotes: 0
Reputation: 26511
You can throw exceptions in JS by just passing objects to throw
. So throw err
in your case.
Upvotes: 1