在try块中分配值的最佳方法

Ave*_*235 10 javascript functional-programming ecmascript-6

let x;
try {
  x = ...;
} catch (e) { 
  return
}

// rest of the code that uses `x`
const y = x + ...;
Run Code Online (Sandbox Code Playgroud)

x只分配一次,但我必须使用let而不是const.

另一种方式是:

try {
  const x = ...;
  // rest of the code that uses `x`
  const y = x + ...;
} catch (e) { 
  return
}
Run Code Online (Sandbox Code Playgroud)

但是,这会增加嵌套并使得不清楚什么会引发错误.

有没有更好的办法?

我不必关心x如果try失败的价值,因为我将在catch块中返回.
我也不想将它解压缩到单独的函数中.

Cer*_*nce 1

每当我遇到这样的事情时,我都会使用一个函数:

function constTryCatch(valueFn, catchFn) {
  try {
    return valueFn();
  } catch (e) {
    if (catchFn) catchFn(e);
    return null;
  }
}

const obj = { foo: 'bar' };
const x = constTryCatch(() => obj.foo);
console.log(x);
const y = constTryCatch(() => obj.foo.bar.baz, (e) => console.log(e));
console.log(y);
// example, if the rest of the block depends on `y` being truthy:
// if (!y) return;
Run Code Online (Sandbox Code Playgroud)

请注意,堆栈片段无法正确显示错误。在真实的浏览器控制台中,你会看到类似这样的内容:

酒吧

类型错误:无法在 constTryCatch ((index):79) at constTryCatch ((index):69) at window.onload ((index):79) 读取未定义的属性“baz”

无效的

  • 啊,没注意到这一点。然而,它只检查“y”是否为真,而不检查是否没有抛出错误。如果我希望代码能够使用“.baz”的任意值(包括虚假值),我需要一个额外的标志。 (3认同)
  • 这不会中止(从整个代码中返回),尽管在“catch”情况下,它确实将“null”分配给“x”并继续。 (2认同)