try...catch
基础用法
function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
try {
thisThrows();
} catch (e) {
console.error(e);
} finally {
console.log("We do cleanup here");
}
// Output:
// Error: Thrown from thisThrows()
// ...stacktrace <-- 这里是错误堆栈,用于查看调用栈(下文同)
// We do cleanup here
捕获 Promise 错误
Case #1: try...catch
捕获
async function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
async function run() {
try {
await thisThrows(); // <-- await 这个 Promise
} catch (e) {
console.error(e);
} finally {
console.log("We do cleanup here");
}
}
run();
// Output:
// Error: Thrown from thisThrows()
// ...stacktrace
// We do cleanup here
Case #2: .catch()
捕获
async function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
thisThrows()
.catch(console.error)
.then(() => console.log("We do cleanup here"));
// Output:
// Error: Thrown from thisThrows()
// ...stacktrace
// We do cleanup here
捕获嵌套 Promise 错误
async function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
async function myFunctionThatCatches() {
try {
// 使用 `await` 捕获嵌套函数中的第一个错误
return await thisThrows();
} catch (e) {
console.error(e);
} finally {
console.log("We do cleanup here");
}
return "Nothing found";
}
async function run() {
const myValue = await myFunctionThatCatches();
console.log(myValue);
}
run();
// Outptut:
// Error: Thrown from thisThrows()
// ...stacktrace
// We do cleanup here
// Nothing found
重置错误堆栈
堆栈丢失问题
function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
function myFunctionThatCatches() {
try {
return thisThrows();
} catch (e) {
throw new TypeError(e.message);
} finally {
console.log("We do cleanup here");
}
}
async function run() {
try {
await myFunctionThatCatches();
} catch (e) {
console.error(e);
}
}
run();
// Outputs:
// We do cleanup here
// TypeError: Error: Thrown from thisThrows()
// at myFunctionThatCatches (/repo/error_stacktrace_1.js:9:15) <-- 错误指向 `try catch` 块
// at run (/repo/error_stacktrace_1.js:17:15)
// at Object.<anonymous> (/repo/error_stacktrace_1.js:23:1)
⚠️第28行,错误显示仅捕获到了 myFunctionThatCatches
块的错误。
如何解决
function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
function myFunctionThatCatches() {
try {
return thisThrows();
} catch (e) {
// !! 也许先在这里做其他事情
throw e;
} finally {
console.log("We do cleanup here");
}
}
async function run() {
try {
await myFunctionThatCatches();
} catch (e) {
console.error(e);
}
}
run();
// Outputs:
// We do cleanup here
// Error: Thrown from thisThrows()
// at thisThrows (/repo/error_stacktrace_2.js:2:11) <-- 注意,我们现在指向实际错误的来源
// at myFunctionThatCatches (/repo/error_stacktrace_2.js:7:16)
// at run (/repo/error_stacktrace_2.js:18:15)
// at Object.<anonymous> (/repo/error_stacktrace_2.js:24:1)
⚠️29 行捕获到了嵌套在 myFunctionThatCatches
内部的错误 thisThrows
。
运行环境
报错:ReferenceError: regeneratorRuntime is not defined
原因:async/await 需要配置运行环境
解决:
npm i regenerator-runtime -D
// 入口文件
import "regenerator-runtime/runtime.js";