尝试捕获语句中的错误

时间:2019-07-24 11:26:24

标签: javascript promise async-await try-catch

我正在使用async await,从一个函数到另一个带有try catch语句的函数来捕获错误。 function1function2在不同的文件上:

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语句

2 个答案:

答案 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);