Strawman: `Function.prototype.try` (or `Function.try`)

Isiah Meadows isiahmeadows at
Tue Aug 22 17:01:52 UTC 2017

Usually, it's most convenient to just let errors easily fall through,
using `try`/`catch`/`finally`. But when you're writing more low-level
error-handling code, especially where errors are never exceptional
(like test errors in a testing framework or task errors in a
distributed worker pool implementation), it's often easier to handle
completions/results as if they were values, like how Lua [1] and Rust
[2] handle it.


Here's my proposal: introduce either `Function.try(func, thisArg,
...args)` or `Function.prototype.try(thisArg, ...args)`. It works much
like ``, except instead of returning/throwing,
it always returns a `{thrown, value}` pair.

Polyfilling either would be easy:

Function.try = (func, thisArg, ...args) => {
    try {
        return {thrown: false, value:, ...args)}
    } catch (e) {
        return {thrown: true, value: e}

Function.prototype.try = function (thisArg, ...args) {
    try {
        return {thrown: false, value:, ...args)}
    } catch (e) {
        return {thrown: true, value: e}

Engines could make this much more performant, though, by detecting the
function, avoiding the object allocation if immediately destructured,
optimizing the arguments like ``, and if called
with a lambda, inlining the whole thing into a pseudo-`try`/`catch`.


Isiah Meadows
me at

Looking for web consulting? Or a new website?
Send me an email and we can get started.

More information about the es-discuss mailing list