我正在使用async
await
,从一个函数到另一个带有try
catch
语句的函数来捕获错误。 function1
和function2
在不同的文件上:
function1 = async (req, res) => {
try {
const foo = await function2(req.body.name);
res.status(200).send(foo);
} catch (e) {
res.status(500).send(e);
}
}
function2 = async (name) => {
try {
const result = await db.find({name: name});
if (result) return result;
} catch (e) {
return e;
}
}
如果错误发生在db.find
中,它将捕获function2
语句。如何确保如果涉及function2
的catch语句,则返回去function1
的catch语句
答案 0 :(得分:1)
使用throw将错误发送到上级函数,您可以这样做
function2 = async (name) => {
try {
const result = await db.find({name: name});
if (result) return result;
} catch (e) {
// do some logging if needed, like
console.log(e);
throw e;
}
}
如果您在function2中未执行任何日志记录或错误处理,则不应该使用try catch,它会直接由function1处理
function2 = async (name) => {
const result = await db.find({name: name});
if (result) return result;
}
答案 1 :(得分:0)
只需使用throw e
这是代码段
// test wrapper
let db = { find: (x) => new Promise((res,rej)=>setTimeout(x=>rej('NO DATA'),1000)) }
function1 = async (req, res) => {
try {
console.log('Find...');
const foo = await function2('abc');
console.log('func1');
} catch (e) {
console.log('outer err', e);
}
}
function2 = async (name) => {
try {
const result = await db.find({name: name});
console.log('func2');
} catch (e) {
console.log('inner err', e);
throw e;
}
}
function1(0,0);