nodejs 函数中的域错误处理程序装饰器
Domain error handler decorators in nodejs functions
我正在尝试为我的节点 js 函数编写装饰器。像
'Test func a': custom_decorator( func(x)){
..
..
..
})
假设我想将域错误处理程序添加到我的函数中,我想将域错误处理抽象到我的所有函数中..
var d = domain.create().on('error', function(err) {
console.error(...);
});
d.enter();
"My function"
d.exit()
我想将错误处理移至装饰器,以便函数编写者可以使用
调用它
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
其中:
更新
另一个带有 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
我正在尝试为我的节点 js 函数编写装饰器。像
'Test func a': custom_decorator( func(x)){
..
..
..
})
假设我想将域错误处理程序添加到我的函数中,我想将域错误处理抽象到我的所有函数中..
var d = domain.create().on('error', function(err) {
console.error(...);
});
d.enter();
"My function"
d.exit()
我想将错误处理移至装饰器,以便函数编写者可以使用
调用它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
其中:
更新
另一个带有 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