How to recover from errors in rxjs?

烂漫一生 提交于 2019-12-23 17:58:43

问题


I'm trying to understand how to consume observable sequences and how to recover from errors.

My example is a bit contrived but my real implementation is a bit too complex to show here. Anyway, I have someObservable that emits values when the user clicks in the UI. This should trigger a request to the API (GET/POST/etc). The problem is that if the API returns an error, postData isn't called anymore after that.

I've make an example here that shows the problem. I've found that I can use Rx.Observable.of instead of Rx.Observable.throw to keep things running. But that will emit a value to the subscribe function. And in my real application postData is a service that is reused by multiple parts of the application and I'm not sure that I want to use of instead of throw there.

So my question is, how do you normally handle things like these?

let someObservable = Rx.Observable.timer(1, 1000);

someObservable
.switchMap(data =>  {
  return postData(data);
})
.catch(error => {
  console.log("POST failed");
})
.subscribe(val => console.log("Success: " + val));

function postData(data) {
  console.log("Will post " + data);

  if (data !== 2) {
    return Rx.Observable.of(true);
  }
  else {
    return Rx.Observable.throw(new Error("400 Bad Request or something"));
  }
}

http://jsbin.com/naroyeyive/3/edit?js,console


回答1:


If you want to send the request again, you may want to look into retry and retryWhen instead of catch.

catch will use the returned Observable as new "source". See this bin for an example.

retry(When) will "re-subscribe" whenever an error occurs, based on the configuration you pass to the operators. You can find examples and more information here: https://www.learnrxjs.io/operators/error_handling/retrywhen.html



来源:https://stackoverflow.com/questions/42642966/how-to-recover-from-errors-in-rxjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!