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

nodejs handle exception in events handler: 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