0

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
    }
  }
claudiomatiasrg
  • 566
  • 3
  • 11
  • 24
  • 2
    You need to do `catch(err) {` for it to work, or else this statement `err.message;` will generate an error of its own. – Ason Jun 26 '18 at 16:32
  • This looks related, maybe it's a duplicate: https://stackoverflow.com/questions/30649994/can-i-catch-an-error-from-async-without-using-await – Barmar Jun 26 '18 at 16:48

1 Answers1

0

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.

vkarpov15
  • 2,465
  • 18
  • 17
  • thanks for your reply! I tried your solution but its not working. I get `UnhandledPromiseRejectionWarning` when `calledFunction()` runs – claudiomatiasrg Jun 26 '18 at 17:47