简体   繁体   中英

Coming to catch if a statement in try gives error

I am using async await , from one function to another with try catch statements for catching errors. Here function1 and function2 are on different files:

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;
    }
}

If the error comes in the db.find it goes to catch statement of function2 . How to make sure that if it comes to catch statement of function2 then the return goes to catch statement of function1

Use throw to send error to upper level functions, in your case you can do

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;
    }
}

also if you are not doing any logging or error handling in function2 you should not use try catch, it will directly handled by function1

function2 = async (name) => {
         const result = await db.find({name: name});
        if (result) return result;
}

Just use throw e here is snippet

 // 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM