节点asynchronous和exception处理

我正在使用asynchronous瀑布。 当我的一个函数调用callback(err)时,我的自定义asynchronouscallback被调用。 在那里,我抛出一个错误,希望它会在asynchronous尝试块中被捕获,但是这没有发生。

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()"); } } 

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

希望它会在asynchronous的try块中被捕获,但是这没有发生

这不可能。 错误将被创build并asynchronous抛出,即在async.waterfall返回并且try块被留下之后很长时间。 如果你想处理一个asynchronous错误,在myAsyncCallback (就像你已经做的那样)。 切勿throwasynchronouscallback。

为我工作。 你看到有什么不同吗? 如果有更多的话,我会更新我的答案。

这是我的输出:

 [Clays-MacBook-Pro ~/Documents/workspace/scratch]:node index.js inside function1 This code gets executed. This code gets executed too. THIS CODE IS NEVER EXECUTED. [Clays-MacBook-Pro ~/Documents/workspace/scratch]:node -v v6.9.1 [Clays-MacBook-Pro ~/Documents/workspace/scratch]: 

这个代码:

 var async = require('async') try { async.waterfall([function1, function2], myAsyncCallback); } catch(err) { console.log("THIS CODE IS NEVER EXECUTED."); } function function1(callback) { console.log("inside function1"); var errMsg = "Uh oh"; callback(new Error(errMsg), errMsg); } function function2(stuff2, callback) { console.log('inside function2'); var errMsg = "Uh oh"; callback(new Error(errMsg), errMsg); } 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()"); } console.log(result); }