nodejs函数中的域error handling程序装饰器

我正在尝试为我的节点js函数编写一个装饰器。 就像是

'Test func a': custom_decorator( func(x)){ .. .. .. }) 

假设我想为我的函数添加域error handling程序,我想抽象域error handling到我所有的function..

 var d = domain.create().on('error', function(err) { console.error(...); }); d.enter(); "My function" d.exit() 

我想将error handling移动到一个装饰器,以便函数作者可以使用它来调用它

 function_name : errorDecorator(fn) 

一个例子:

 function sum(a, b) { return a + b; } function logDecorator(fn) { return function() { console.log(arguments); return fn.apply(this, arguments); }; } var sumLog = logDecorator(sum); sumLog(1, 10); // returns 11 and logs { '0': 1, '1': 10 } to the console sumLog(5, 4); // returns 9 and logs { '0': 5, '1': 4 } to the console 

哪里:

  • arguments是一个与传递给logDecorator的参数相对应的数组对象。
  • fn.apply使用给定的this值和作为一个数组(或类似数组的对象)提供的参数fn.apply调用一个函数。

UPDATE

try-catch的另一个例子是:

 function div(a, b) { if(b == 0) throw new Error("Can't divide by zero."); else return a / b; } function logDecorator(fn) { return function() { try { console.log(arguments); return fn.apply(this, arguments); } catch(e) { console.error("An error occurred: " + e); } }; } var divLog = logDecorator(div); divLog(5, 2); // returns 2.5 and logs { '0': 5, '1': 2 } to the console divLog(3, 0); // returns undefined, logs { '0': 3, '1': 0 }, and "An error occurred: Error: Can't divide by zero." to the console