![](/img/trans.png)
[英]Realm JS Try...Catch block returns both error and success promises
[英]Is it possible to capture all JS exceptions by running all the code try...catch block?
为什么人们不在一个大的 try...catch 块中编写他们所有的 JS 代码? 或者更好的是,将所有代码集中在一个函数中,并通过从 try...catch 块中调用该函数来启动您的程序。 为什么这不是常态? 有什么收获?
function allMyJSCode() {
console.log("I can get here");
foo.bar = ""; //accessing property of uninitialized object
console.log("but never here");
}
try {
allMyJSCode();
} catch(error) {
console.log("Error from allMyJSCode: " + error);
}
//I can get here
//Error from allMyJSCode: ReferenceError: foo is not defined
因为一旦发生错误,其余的代码将不会被执行,它将直接进入catch
块并忽略可能很重要的代码。 你不想那样。
想象一下这个场景:
// Important code #1
// Important code #2
现在,如果您将这两个组合在一个巨大的try...catch
并且出于某种原因Important code #1
抛出错误,那么Important code #2
将永远不会被执行并可能导致问题,而如果这些代码中的每一个都包含在它们的自己的try...catch
,那么无论在Important code #1
发生什么,都会到达并执行Important code #2
。
Important code #1
可能像更改元素的背景一样微不足道,它可能会阻止执行处理填充数据、发送请求等的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.