Strawman: `Function.prototype.try` (or `Function.try`)
Isiah Meadows
isiahmeadows at gmail.com
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.
[1]: https://www.lua.org/pil/8.4.html
[2]: https://doc.rust-lang.org/book/second-edition/ch09-02-recoverable-errors-with-result.html
Here's my proposal: introduce either `Function.try(func, thisArg,
...args)` or `Function.prototype.try(thisArg, ...args)`. It works much
like `Function.prototype.call`, except instead of returning/throwing,
it always returns a `{thrown, value}` pair.
Polyfilling either would be easy:
```js
Function.try = (func, thisArg, ...args) => {
try {
return {thrown: false, value: func.call(thisArg, ...args)}
} catch (e) {
return {thrown: true, value: e}
}
}
Function.prototype.try = function (thisArg, ...args) {
try {
return {thrown: false, value: this.call(thisArg, ...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 `Function.prototype.call`, and if called
with a lambda, inlining the whole thing into a pseudo-`try`/`catch`.
-----
Isiah Meadows
me at isiahmeadows.com
Looking for web consulting? Or a new website?
Send me an email and we can get started.
www.isiahmeadows.com
More information about the es-discuss
mailing list