cannot catch error in function called inside try catch block

835 views Asked by At

I'm having trouble with some asynchronous functions in a nodejs server. This is the first time that I deal with try/catch blocks and I cannot catch the error inside the called function.

my code:

calledFunction: async function() {
    try{
      //DO SOMETHING THAT RETURNS AN ERROR
    }
    catch(error) {
      //NEED TO CATCH THIS ERROR IN mainFunction()
      var error = {};
      error.error = err.message;
      return error;
    }
}

mainFunction: async function () {
    try {
      await this.calledFunction();
      return true;
    }
    catch(error) {
      var error = {};
      error.error = err.message;
      return error
    }
  }
1

There are 1 answers

1
vkarpov15 On BEST ANSWER

You need to rethrow the error in your catch block.

try{
  //DO SOMETHING THAT RETURNS AN ERROR
}
catch(error) {
  //NEED TO CATCH THIS ERROR IN mainFunction()
  var error = {};
  error.error = err.message;
  throw error; // Rethrow
}

My blog has more info on using async/await with try/catch if you want to learn more.