【问题标题】:How catch Errors with try catch of lower order functions如何使用低阶函数的 try catch 捕获错误
【发布时间】:2021-01-26 22:24:10
【问题描述】:
我试图从一个函数中捕获错误,该函数会导致另一个函数返回错误。示例:
async function method1 () {
throw new Error('method1 error')
return 'result'
}
async function method2 () {
const result = await method1()
return result
}
async function method3 () {
try {
const result = await method2()
} catch (error) {
console.log(error)
}
}
method3()
如何在方法 3 中捕获方法 1 的错误?
【问题讨论】:
标签:
javascript
try-catch
throw
【解决方案1】:
async function method1() {
try {
// do whatever you have to
throw new Error('method1 error'); // <= to be deleted
} catch (error) {
throw new Error('method1 error'); // generate the custom error
}
}
async function method2() {
try {
const result = await method1();
return result
} catch (error) {
throw error; // "forward" any error
}
}
async function method3() {
try {
const result = await method2();
} catch (error) {
console.log(error.message);
}
}
method3();