非同步錯誤處理

試著抓

必須始終處理錯誤。如果你使用的是同步程式設計,則可以使用 try catch。但是如果你非同步工作,這不起作用! 例:

try {
    setTimeout(function() {
        throw new Error("I'm an uncaught error and will stop the server!");
    }, 100); 
}
catch (ex) {
    console.error("This error will not be work in an asynchronous situation: " + ex);
}

非同步錯誤只能在回撥函式內處理!

工作機會

Version <= V0.8

事件處理程式

Node.JS 的第一個版本有一個事件處理程式。

process.on("UncaughtException", function(err, data) { 
    if (err) {
        // error handling
    }
});
Version => V0.8

在域內,錯誤通過事件發射器釋放。通過使用這些都是錯誤,定時器,回撥方法隱式只在域內註冊。如果發生錯誤,則傳送錯誤事件並且不會使應用程式崩潰。

var domain = require("domain");
var d1 = domain.create();
var d2 = domain.create();

d1.run(function() {
    d2.add(setTimeout(function() {
        throw new Error("error on the timer of domain 2");
    }, 0));
});

d1.on("error", function(err) {
    console.log("error at domain 1: " + err);
});

d2.on("error", function(err) {
    console.log("error at domain 2: " + err);
});