Search code examples
node.jstry-catch

Async/Await nested try/catch


I have two similiar functions foo and bar that looks like this

async function foo() {
    try {
        await postRequest() 
    } catch (error) {
        throw error
    }

async function bar() {
    try {
        await anotherReq() 
    } catch (error) {
        // handle error
    }

I want to call foo first, handle the error by calling bar, then handle eventual bar errors again.

So i tried to do this

try {
    await foo();
} catch (error) {
    try {
        await bar()
    } catch(error) {
        // handle error
    }
}

But it's obviously ugly because of the nesting. Any workaround ?


Solution

  • What I usually do with async/await to avoid the nesting is to return tupels of [result, error] instead of try/catch blocks.

    So in this case my code would look something like this:

    async function foo() {
      const response = await postRequest();
    
      if (response.ok) {
        return  [response, null];
      }
    
      return [null, "error"];
    }
    
    async function bar() {
      const response = await anotherReq();
    
      if (response.ok) {
        return  [response, null];
      }
    
      return [null, "error"];
    }
    
    // call functions
    const [res, err] = await foo();
    
    if (err) {
      const [res, err] = await bar();
    }