user994165 user994165 - 20 days ago 5
Node.js Question

Node async and exception handling

I'm using async waterfall. When one of my functions calls callback(err), my custom async callback is called. Inside of there I throw an error, hoping it will be caught in the try block around async, but that's not happening.

try {
async.waterfall([function1, function2], myAsyncCallback);
}
catch(err) {
console.log("THIS CODE IS NEVER EXECUTED.");
}

var function1 = function() {
...
//some error occurs:
callback(new Error(errMsg), errMsg);
...
}

var function2 = function() {
...
}

function myAsyncCallback(err, result) {
console.log("This code gets executed.");
if (err) {
console.log("This code gets executed too.");
throw new Error("I want this error caught at the top around the catch around async.waterfall()");
}
}

Answer

https://runkit.com/imjosh/async-try-catch/2.0.0

var async = require('async');

try {
  async.waterfall([function1, function2], myAsyncCallback);
}
catch(err) {
  errorHandler(err);
}

function function1(callback) {
  console.log('in fn1')   
  callback(null,'fn1');   
}

function function2(fn1, callback) {
  console.log('in fn2')
  callback(null, fn1 + 'fn2');
}

function myAsyncCallback(err, result) {
    if (err) {
      console.error('There was an error: ' + err);
      return;
    }
    //an error occurs. this gets caught by the outer try block
    //var foo = outer; //oops, outer is not defined. This throws an error

    //same scenario but inside an async function
    //can't/won't be caught by the outer try block
    setTimeout(function(){ 
        try{ //need try here
          var foo = inner; //oops, inner is not defined. This throws an error
        } 
        catch(err) {
          errorHandler(err);
       }
    }, 1000);

    console.log('Result was: ' + result);
}

function errorHandler(err){ 
  //Make error handler a function that can be called from either catch
  console.log('caught error: ' + err);
}