What I really want for the expression to return the value, but give a branch for the error case:
// We still get a catch block to handle errors in
const value = try foo() catch (e) {
throw new MyError('Error trying to foo');
};
Otherwise we have to write this to handle the error: const [value, error] = try foo();
if (error) {
throw new MyError('Error trying to foo');
}
And it's far to easy to forget the error handling code altogether, resulting in silent failures.edit: removed a brain-fart on a case that's already handled by JS :O
foo?.bar = 42;
This would not perform the assignment if an optionally chained value was nullish. It downlevels to foo == null ? undefined : foo.bar = 42;
Given that the assignment is a SyntaxError now, this should be possible.
Try/catch and exceptions seem to be tough for programmers to handle. You have to have disciplined unwinding for exception propagation to work well when an unwind goes through multiple calls.
Rust's rather simple "?" operator, which I once thought was underpowered, seems to be a workable solution. It's just syntactic sugar for return on error, but because there's a standard error trait, that usually works out well.
The lesson from this is to get your error objects right early in the history of a language, because you can't retrofit them. Once you have that right, how to report errors becomes sane, and the mechanism becomes less important.
[val, err] ?= maybeThrow(); // instead of this
[val, err] = wrapErr(maybeThrow); // you can write wrapErr yourself and use it forever
[val, err] = wrapErr(maybeThrow, arg1, arg2); // you can even provide args
Try expressions (mentioned in other comments) seem significantly better, but still feel like they're trying to tack on something that fits awkwardly into the original language design (though that's kind of the history of JavaScript)
Anyway, I'd use those all the time if they landed
Just use var, then.
Given that the (much simpler) throw expressions have been stuck in bureaucratic hell for 7 years, I look forward to seeing try expressions some time around the heat death of the universe.