Javascript 如果try中的语句出错,则捕获

Javascript 如果try中的语句出错,则捕获,javascript,promise,async-await,try-catch,Javascript,Promise,Async Await,Try Catch,我正在使用asyncwait,通过trycatch语句从一个函数到另一个函数捕捉错误。这里的function1和function2位于不同的文件中: function1 = async (req, res) => { try { const foo = await function2(req.body.name); res.status(200).send(foo); } catch (e) { res.status(500)

我正在使用
async
wait
,通过
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
的catch语句。如何确保如果是函数2的catch语句,则返回函数1的catch语句。在您的情况下,可以使用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;
}

只需使用
throw e
以下是代码片段

//测试包装器
让db={find:(x)=>newpromise((res,rej)=>setTimeout(x=>rej('NO DATA'),1000))}
功能1=异步(请求、恢复)=>{
试一试{
log('Find…');
const foo=等待函数2(“abc”);
console.log('func1');
}捕获(e){
console.log('outer err',e);
}
}
function2=异步(名称)=>{
试一试{
const result=await db.find({name:name});
console.log('func2');
}捕获(e){
console.log('internalerr',e);
投掷e;
}
}

函数1(0,0)嗯,不
返回错误吗?如果不抛出异常(或拒绝承诺),则不会运行
catch
语句。在
函数2中尝试
/
catch
有什么意义?