nodejs在事件处理程序中处理异常:safeway?



还有另一种真正的方法,在nodejs事件不安全处理程序中做安全处理异常?我不能控制事件处理程序,但应用程序必须在其中出现错误后运行。

var someUnsafeEventHandler = function(){ throw "throw!"; };
var MySafeEventHandler = function(f){
return function(){
try{ 
f.apply(f,arguments);
}catch(e){
console.warn("MySafeEventHandler handle error: "+e);
};
}
}
var EventEmitter = require('events');
var myEmitter = new EventEmitter();
myEmitter.on('event', new MySafeEventHandler(someUnsafeEventHandler));
myEmitter.on('event', someUnsafeEventHandler);
console.log("== start test ==");
myEmitter.emit('event');
console.log("== test passed =="); // never printed by exception in someUnsafeEventHandler

输出:

== start test ==
MySafeEventHandler handle error: throw!
/tmp/test_events.js:5
var someUnsafeEventHandler = function(){ throw "throw!"; };
^
throw!

吞下错误是不好的做法,因此最好将错误重定向到EventEmitter中定义的特殊error事件。

var someUnsafeEventHandler = function(){ throw "throw!"; };
const safeHandler= (f)=> function(){
try{
f.apply(this, arguments);
}catch(e){
this.emit('error', e);
}
}
var EventEmitter = require('events');
var myEmitter = new EventEmitter();
// catch errors
myEmitter.on('error', e=> console.log(`Caught: ${e}`));
myEmitter.on('event', safeHandler(someUnsafeEventHandler));
myEmitter.on('event', ()=> console.log('second listener'));
console.log("== start test ==");
myEmitter.emit('event');
console.log("== test passed ==");

输出:

== start test ==
Caught: throw!
second listener
== test passed ==
Process finished with exit code 0

相关内容

  • 没有找到相关文章

最新更新