Proposal: Conditional `catch` in Promises
T.J. Crowder
tj.crowder at farsightsoftware.com
Tue Apr 24 10:03:18 UTC 2018
For my part, if we're going to get into optional catching, I'd rather see a
common approach between promise `catch` and `try`/`catch`. There have been
various discussions about optional/filtered `catch` on the list ([here][1]
and [here][2], probably others).
Your approach is easily implemented in userland:
```js
const cif = (predicate, handler) => e => {
if (predicate(e)) {
return handler(e);
}
throw e;
};
```
then
```js
somePromise
.catch(cif(reason => reason instanceof ValidationError, reason =>
handleValidationError(reason))) // handle ValidationErrors
.catch(cif(reason => reason instanceof InternalError, reason =>
handleInternalError(reason))) // handle InternalErrors
.catch(cif(reason => handleOtherErrors(reason))); // catch all others
```
https://jsfiddle.net/maov8y0h/
To be clear, I'm not saying that just because something can be implemented
in userland, it shouldn't be considered. (Lots of things can be implemented
in userland.) But again, I'd want to see a cohesive approach, and I think
this probably doesn't take us in that direction.
-- T.J. Crowder
[1]: https://esdiscuss.org/topic/standardizing-conditional-try-catch
[2]: https://esdiscuss.org/topic/filtered-promise-catch
On Tue, Apr 24, 2018 at 10:35 AM, Ayush Gupta
<ayushg3112 at gmail.com> wrote:
> I propose that in `Promises`, we accept another function which returns a
> `boolean` as an argument to `catch`. It will enable us to write code like
> this:
>
> ```js
> return somePromise
> .catch((reason) => reason instanceof ValidationError, reason =>
> handleValidationError(reason)) // handle ValidationErrors
> .catch((reason) => reason instanceof InternalError, reason =>
> handleInternalError(reason)) // handle InternalErrors
> .catch(reason => handleOtherErrors(reason)) // catch all others
> ```
>
> If the passed function evaluates to `true`, call the actual rejection
> handler. If none of the catch are eligible to handle the rejection, it
> causes an unhandled rejection.
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180424/783bc9e5/attachment.html>
More information about the es-discuss
mailing list