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块中返回.
我也不想将它解压缩到单独的函数中.
每当我遇到这样的事情时,我都会使用一个函数:
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”
无效的