我几天前刚开始尝试node.js.我已经意识到只要我的程序中有未处理的异常,Node就会终止.这与我所暴露的普通服务器容器不同,只有当未处理的异常发生且容器仍然能够接收请求时,工作线程才会死亡.这引出了一些问题:
process.on('uncaughtException')防范它的唯一有效方法吗?process.on('uncaughtException')在异步进程执行期间是否会捕获未处理的异常?我将非常感谢任何指针/文章,它将向我展示在node.js中处理未捕获的异常的常见最佳实践
处理此方案的最佳方法是什么.我处于受控环境中,我不想崩溃.
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
setTimeout(function(){
throw new Error("AJAJAJA");
}, 500);
});
}
var p = getPromise();
p.then(function(){
console.log("Yay");
}).error(function(e){
console.log("Rejected",e);
}).catch(Error, function(e){
console.log("Error",e);
}).catch(function(e){
console.log("Unknown", e);
});
Run Code Online (Sandbox Code Playgroud)
从setTimeout中抛出时,我们总是得到:
$ node bluebird.js
c:\blp\rplus\bbcode\scratchboard\bluebird.js:6
throw new Error("AJAJAJA");
^
Error: AJAJAJA
at null._onTimeout (c:\blp\rplus\bbcode\scratchboard\bluebird.js:6:23)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
Run Code Online (Sandbox Code Playgroud)
如果抛出发生在setTimeout之前,那么bluebirds catch会把它拿起来:
var Promise = require('bluebird');
function getPromise(){
return new Promise(function(done, reject){
throw new Error("Oh no!");
setTimeout(function(){
console.log("hihihihi")
}, 500);
});
}
var p = getPromise();
p.then(function(){ …Run Code Online (Sandbox Code Playgroud) 我知道如何处理promises中的特定错误但我有时会看到如下代码片段:
somePromise.then(function(response){
otherAPI(JSON.parse(response));
});
Run Code Online (Sandbox Code Playgroud)
有时,我得到无效的JSON,这会在JSON.parse throws 时导致静默失败.一般来说,我必须记住.catch在我的代码中为每个承诺添加一个处理程序,当我不在时,我无法找到我忘记的地方.
如何在代码中找到这些被抑制的错误?