Joel
Joel

Reputation: 8938

How to recover from errors in rxjs?

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

Upvotes: 3

Views: 2163

Answers (1)

Sebastian Sebald
Sebastian Sebald

Reputation: 16846

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

Upvotes: 4

Related Questions