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
<ayushg3...@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@mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
_______________________________________________
es-discuss mailing list
es-discuss@mozilla.org
https://mail.mozilla.org/listinfo/es-discuss

Reply via email to