Warning:我不会推荐使用域的原始答案,将来域将被弃用,我在编写原始答案时获得了很多乐趣,但我不再相信它太相关了。相反 - 我建议使用事件发射器和具有更好错误处理能力的承诺 - 下面是带有承诺的示例。这里使用的承诺是Bluebird https://github.com/petkaantonov/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);
});
它也像同步代码的普通 catch 一样工作
atry(function() {
throw "something";
}).catch(function(err){
console.log("caught "+err);
});
我希望得到有关解决方案的一些反馈
附带说明一下,在 v 0.8 中,显然当你捕获域中的异常时,它仍然会冒泡process.on("uncaughtException")
。我在我的process.on("uncaughtException")
with
if (typeof e !== "object" || !e["domain_thrown"]) {
然而,文档建议反对process.on("uncaughtException")
any way