2013-07-26 16 views
4

我正在使用第三方庫。哪個節點使用節點domain進行錯誤處理。 如果傳遞給該第三方庫的回調函數有任何錯誤,最終會多次調用我的回調函數。如何在具有域的節點中進行適當的錯誤處理?

示例代碼:

var startFunction = function (callback) { 
    //Call thirdParty function and wait for response 
    thirdPartyFunction(function (error, data) { 
    console.log("Called with"); 
    console.log(arguments); 
    //Assume there is an error in my callback function 
    setTimeout(function() { 
     dd 
     callback.apply(null); 
    }, 2000); 
    }); 
} 
//ThirdParty function don't modify anything here 
var thirdPartyFunction = function (callback) { 
    var Domain = require("domain"); 
    var d = require('domain').create(); 
    d.on('error', function (er) { 
    console.log("hi"); 
    callback.apply(null, er); 
    }); 
    d.run(function() { 
    setTimeout(function() { 
     callback.apply(null, [null, "Hello"]); 
    }, 1000); 
    }); 
}; 
startFunction(function() { 
    console.log("Got response") 
}); 

我們報告這個錯誤給第三方lib和他們已經修改了源代碼。如:

d.on('error', function (er) { 
    if (isCalled == false) { 
    isCalled = true; 
    } else { 
    return; 
    } 
    console.log("hi"); 
    callback.apply(null, er); 
}); 

現在解決了多次調用函數的問題。但最終的回調永遠不會被調用。

如何處理節點的這種行爲?

如果第三方lib修改了代碼,導致應用程序崩潰。放置一個包裝域也沒有幫助。

d.on('error', function (er) { 
    if (isCalled == false) { 
    isCalled = true; 
    } else { 
    throw new Error("Getting called"); 
    return; 
    } 
    console.log("hi"); 
    callback.apply(null, er); 
}); 

在節點中處理這種情況的最佳方法是什麼?

+0

爲什麼調用修復不起作用?它在哪裏設置?當回調被調用時它沒有設置? – Murukesh

回答

1

您可以將自己的域名監聽到你的回調函數,像這樣:

var startFunction = function (callback) { 
    //Call thirdParty function and wait for response 
    thirdPartyFunction(function (error, data) { 
    var d1 = require('domain').create(); 
    d1.on('error', function(er){ 
     console.log("bye"); 
     callback.apply(null, er); 
    }); 
    d1.run(function() { 
     console.log("Called with"); 
     console.log(arguments); 
     //Assume there is an error in my callback function 
     setTimeout(function() { 
     dd 
     callback.apply(null); 
     }, 2000); 
    }); 
    }) 
} 

這樣,如果沒有它會被你的處理程序捕獲錯誤,該錯誤將被送回到主並且不會陷入無限循環。

相關問題