For the function below, how can I throw an error from the 'BROKEN' like that can be handled nicely by its subscriber in the same way as the 'WORKS' line of code?
What I'm seeing is that the 'Works' line passes the error neatly this function's subscriber, whereas the BROKEN line just blows up without getting handled by its subscriber. I'm using Angular (version 5.0.3) in an Ionic project, RXJS version 5.5.2, and the HttpClient in @angular/common/http.
public makeRequest(requestParameters) {
return Observable.create(observer => {
let url = 'http://example.com/service/action?a=b';
this.http.get(url,{withCredentials: true})
.subscribe(data => {
if(data["success"] !== true)
observer.error("Unexpected result");//BROKEN
else
observer.next(data["payload"]);
},
err => {
console.log('error: ' + err);
observer.error(err);//WORKS
});
});
}
Here's an example of a function that calls the one above:
public getStuffFromServer(){
this.makeRequest({parameters go here}).subscribe(
data => {
//do something with the results
},
err => {
//This never gets called from the 'BROKEN' code (but it does from the WORKS code
}
);
}
Thanks for your help!
OK, it looks like I found the answer on this page: https://codingblast.com/rxjs-error-handling/
The key is to use the map and catch functions like so:
public makeRequest(requestParameters) {
return Observable.create(observer => {
let url = 'http://example.com/service/action?a=b';
this.http.get(url,{withCredentials: true})
.map(data => {
if(data["success"] !== true)
throw new Error("Something meaningful");
return data["payload"];
})
.catch(err => {
return Rx.Observable.throw(err);
});
.subscribe(data => {
observer.next(data);
},
err => {
console.log('error: ' + err);
observer.error(err);
});
});
}
Hopefully this will help somebody. Thank you everyone who answered or gave it some thought!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments