操作顺序加上高级思想
如果没有 try catch 块,未定义的函数将抛出错误并停止执行:
undefinedFunction("This will not get executed");
console.log("I will never run because of the uncaught error!");
将抛出错误而不是运行第二行:
// Uncaught ReferenceError: undefinedFunction is not defined
你需要一个类似于其他语言的 try catch 块,以确保捕获该错误,以便代码可以继续执行:
try {
undefinedFunction("This will not get executed");
} catch(error) {
console.log("An error occured!", error);
} finally {
console.log("The code-block has finished");
}
console.log("I will run because we caught the error!");
现在,我们已经发现了错误并且可以确保我们的代码将要执行
// An error occured! ReferenceError: undefinedFunction is not defined(…)
// The code-block has finished
// I will run because we caught the error!
如果我们的 catch 块发生错误怎么办?
try {
undefinedFunction("This will not get executed");
} catch(error) {
otherUndefinedFunction("Uh oh... ");
console.log("An error occured!", error);
} finally {
console.log("The code-block has finished");
}
console.log("I won't run because of the uncaught error in the catch block!");
我们不会处理 catch 块的其余部分,除了 finally 块之外,执行将暂停。
// The code-block has finished
// Uncaught ReferenceError: otherUndefinedFunction is not defined(…)
你总是可以嵌套你的 try catch 块..但是你不应该因为那会变得非常混乱..
try {
undefinedFunction("This will not get executed");
} catch(error) {
try {
otherUndefinedFunction("Uh oh... ");
} catch(error2) {
console.log("Too much nesting is bad for my heart and soul...");
}
console.log("An error occured!", error);
} finally {
console.log("The code-block has finished");
}
console.log("I will run because we caught the error!");
将捕获前一个示例中的所有错误并记录以下内容:
//Too much nesting is bad for my heart and soul...
//An error occured! ReferenceError: undefinedFunction is not defined(…)
//The code-block has finished
//I will run because we caught the error!
那么,我们怎样才能抓住所有错误!?对于未定义的变量和函数:你不能。
此外,你不应该在 try / catch 块中包装每个变量和函数,因为这些是简单的示例,只有在你修复它们之前才会发生一次。但是,对于你知道的对象,函数和其他变量,但你不知道它们的属性或子进程或副作用是否存在,或者你希望在某些情况下出现某些错误状态,你应该抽象出错误处理以某种方式。这是一个非常基本的示例和实现。
没有受保护的方式来调用不受信任或异常抛出方法:
function foo(a, b, c) {
console.log(a, b, c);
throw new Error("custom error!");
}
try {
foo(1, 2, 3);
} catch(e) {
try {
foo(4, 5, 6);
} catch(e2) {
console.log("We had to nest because there's currently no other way...");
}
console.log(e);
}
// 1 2 3
// 4 5 6
// We had to nest because there's currently no other way...
// Error: custom error!(…)
并有保护:
function foo(a, b, c) {
console.log(a, b, c);
throw new Error("custom error!");
}
function protectedFunction(fn, ...args) {
try {
fn.apply(this, args);
} catch (e) {
console.log("caught error: " + e.name + " -> " + e.message);
}
}
protectedFunction(foo, 1, 2, 3);
protectedFunction(foo, 4, 5, 6);
// 1 2 3
// caught error: Error -> custom error!
// 4 5 6
// caught error: Error -> custom error!
我们捕获错误并仍然处理所有预期的代码,尽管语法稍有不同。无论哪种方式都可行,但是当你构建更高级的应用程序时,你将需要开始考虑抽象错误处理的方法。