警告:我不推荐使用域的原始答案,域将来会被弃用,我写原始答案很有趣,但我不再认为它太相关了。相反 - 我建议使用具有更好错误处理能力的事件发射器和Promise - 这是下面的例子,而不是Promise。这里使用的Promise是Bluebird:
Promise.try(function(){
throw new Error("Something");
}).catch(function(err){
console.log(err.message); // logs "Something"
});
超时(请注意,我们必须返回 Promise.delay):
Promise.try(function() {
return Promise.delay(1000).then(function(){
throw new Error("something");
});
}).catch(function(err){
console.log("caught "+err.message);
});
使用通用的 NodeJS 函数:
var fs = Promise.promisifyAll("fs"); // creates readFileAsync that returns promise
fs.readFileAsync("myfile.txt").then(function(content){
console.log(content.toString()); // logs the file's contents
// can throw here and it'll catch it
}).catch(function(err){
console.log(err); // log any error from the `then` or the readFile operation
});
这种方法既快速又安全,我建议在以下答案上方使用它,该答案使用可能不会留下来的域。
我最终使用了域,我创建了我调用的以下文件mistake.js,其中包含以下代码:
var domain=require("domain");
module.exports = function(func){
var dom = domain.create();
return { "catch" :function(errHandle){
var args = arguments;
dom.on("error",function(err){
return errHandle(err);
}).run(function(){
func.call(null, args);
});
return this;
};
};
以下是一些示例用法:
var atry = require("./mistake.js");
atry(function() {
setTimeout(function(){
throw "something";
},1000);
}).catch(function(err){
console.log("caught "+err);
});
它也像同步代码的普通捕获一样工作
atry(function() {
throw "something";
}).catch(function(err){
console.log("caught "+err);
});
我将不胜感激有关解决方案的一些反馈
附带说明一下,在 v 0.8 中,显然当您在域中捕获异常时,它仍然冒泡到process.on("uncaughtException"). 我处理这在我process.on("uncaughtException")与
if (typeof e !== "object" || !e["domain_thrown"]) {
但是,文档建议反对process.on("uncaughtException")任何方式