ericelliott / speculation

JavaScript promises are made to be broken. Speculations are cancellable promises.
MIT License
197 stars 9 forks source link

Util for error branching? #3

Open ericelliott opened 7 years ago

ericelliott commented 7 years ago

People think they need separate channels for handling cancellations, but a simple error branching utility could be a better solution. Here's a trivial example:

const handleErrors = (
  fn,
  onCancel = () => {}
) => e => {
  (/Cancelled/.test(e.message)) ?
    onCancel(e) : fn(e);
};

const handler = handleErrors(
  e => console.log(`Not cancelled: ${ e }`),
  c => console.log(`Cancelled: ${ c }`)
);

A handleErrors() utility could be fleshed out to handle custom error predicates, and to handle any number of different kinds of errors.