Exception Coalescing

In some cases, I need to write code that will set a default value if the function I'm calling will throw an error.

try {
  this.authorName = execSync('git config --get user.name').toString();
} catch (e) {
  this.authorName = '';
}

Alternative version of this code could be

this.authorName = '';

try {
  this.authorName = execSync('git config --get user.name').toString();
} catch (e) {}

Now that we have nullish coalesicing operator, I've gotten lazy. It would be nice to have a similair operator, but then for exceptions.

Perhaps something like this (as suggested by my colleague):

this.authorName = execSync('git config --get user.name').toString() !! ''
1 Like

With do expressions it would be:

this.authorName = do { try { execSync("...") } catch(e) { "" } };

which is not that bad IMO. Not sure if "yet another operator" is needed, especially since !! is already commonly used to cast to a boolean.

@Jonas_Wilms thanks for the quick reply. You are right on !! already being used for casting to booleans. That would indeed be confusing, but I think that the do expression distracts too much from what the intention is.

Maybe someone can come up with a better syntax. What about just using the catch keyword?

this.authorName = execSync("...") catch ''
1 Like

Yeah, that's much better IMO. Now the only thing that is unclear is operator precedence, so with

a.b().c = d() + e() catch ''

do errors raised from b, d and e go into the catch branch? Maybe to make this clear and to keep this analogous to try { ... } catch(e) { ... } adding a try in the begining might be also worth considering:

a.b().c = d() + try e() catch '';

Haven't thought about operator precedence to be honest. My opinion would be to not use the try keyword and put the operator precedence between … ?? …(5) and … ? … : …(4). I think that this should be similar in usage as the ?? operator and it's up to the developer to be responsible. Creating complex assignments with multiple operators that have different precedence is always risky.