2014-12-03 19 views
0

我遵循了this question处的推荐解决方案,但我仍然看到错误打破了我的观察者。防止非流式错误打破饮用水手表

由于观察者是这样的:

var through = require('through2'); 
var watch = require('gulp-watch'); 

gulp.task('catchall', function() { 
    return watch('gulpfile.js') 
    .pipe(through.obj(externalFunc)) 
    .on('error', function(err) { 
     console.log('Inside error handler:', err); 
    }); 
}); 

随着externalFunc定义为:

function externalFunc(file, enc, done) { 
    throw new Error("I have been compromised - Abort mission!"); 
} 

我希望看到的输出:

[10:52:51] Starting 'catchall'... 
[10:52:53] gulpfile.js was changed 
Inside error handler: I have been compromised - Abort mission! 

相反,我没有得到任何输出从externalFunc,而是得到标准的错误输出和堆栈跟踪:

[10:52:51] Starting 'catchall'... 
[10:52:53] gulpfile.js was changed 

/my/path/to/gulpfile.js:27 
    throw new Error("I have been compromised - Abort mission!"); 
     ^
Error: I have been compromised - Abort mission! 
    at DestroyableTransform.externalFunc [as _transform] .... 

最重要的是,观察者崩溃。

为什么这个错误没有被on('error')监听器困住,我可以在一个吞咽监视器中如何处理这些错误而不退出?

回答

1

它没有陷入错误侦听器,因为如您所说,这不是流错误。

你实际上抛出一个错误,你节点过程它运行一饮而尽,而不是抓住它,所以它表现为一个uncaughtException和完全崩溃的一切,而不必等待你设置的错误处理程序做它的工作。

只是为了演示,但不推荐,你可以做这样的事情:

process.on('uncaughtException', function (er) { 
    console.error('Throwing error:', er); 
}); 

错误将被记录下来,你一饮而尽手表将仍然运行。

我可能会建议你看看Node Domains来处理你的错误安全问题,但我不知道是否使用uncaughtException是一种非常糟糕的做法。