WICG / observable

Observable API proposal
https://wicg.github.io/observable/
Other
575 stars 14 forks source link

I think `catch` may be a requirement #64

Closed benlesh closed 1 month ago

benlesh commented 1 year ago

We currently aren't providing a way to gracefully handle an error. We do have error handling in the subscription/observer itself, but no way to have the subscription "recover" from a fatal error.

Since subscriptions have ended the moment an error is emitted from an observable, the catch method behaves a lot like catch on promise, meaning that it returns an observable that will switch to whatever observable you map to in its handler in the event of an error.

For example:

// Given this observable that will always error:
const source = button1.on('click').map((e, i) => {
  if (i === 2) {
    throw new Error('boom!');
  }
  return e;
});

// If we catch the error and return a different observable,
// the new observable takes over the subscription.
source.catch((err) => {
  console.error(err);
  // let another button take over
  return button2.on('click');
})
.subscribe({
  next: console.log,
  error: () => { /* never called */ }
});

// If we catch the error and return the same observable, you can
// resume or "retry" that observable
source.catch((err) => {
  console.log(err);
  return source;
})
.subscribe({
  next: console.log,
  error: () => { /* never called */ }
});

// If we catch the error and throw it again, or throw any other error
// The resulting observable still errors
source.catch((err) => {
  throw new Error('Different error!');
})
.subscribe({
  next: console.log,
  error: console.error
});