我正在使用异步 waterfall 。当我的函数之一调用 callback(err) 时,会调用我的自定义异步回调。在那里我抛出一个错误,希望它会被异步周围的 try 块捕获,但这并没有发生。
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);
}
关于javascript - Node 异步和异常处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40661730/