这只是我的代码的示例代码
async function thisThrows() {
throw new Error("Thrown from thisThrows()");
}
async function run() {
try {
await thisThrows();
} catch (e) {
throw new Error(e)
}
}
async function run1() {
try{
await run()
}catch(e){
throw new Error(e);
}
}
run1().catch(error => {
console.log(error);
});
下面的代码片段给了我嵌套的错误输出即Error: Error: Error
Error: Error: Error: Thrown from thisThrows()
at run1 (/Users/saunish/servify/sandbox/error-handling.js:18:15)
我需要输出为
Error: Thrown from thisThrows()
这是因为您正在捕获错误,然后创建新错误并抛出新错误,而不是原始错误。
所有函数实际上都应该重新抛出原来的错误,例如:
async function run() {
try {
await thisThrows();
} catch (e) {
throw e // just rethrow the original
}
}