我对 node.js 很陌生,但我非常喜欢它。但是,我很难理解正确的错误处理。
在网络上有很多关于此的好资源,但它们大多是旧的并且指的是基于回调的编程。我更喜欢使用 promise 。有了 promises,处理错误就更容易了,因为您不必为可能发生的每个操作错误重复代码 - 相反,您只需捕获一次并处理(或传播给调用者)。
然而,在 Node 中,区分错误类型并在发生编程错误时执行正常崩溃和重新启动应用程序非常重要。考虑这个基于回调的代码示例:|
function myFunc (input, cb){
if(typeof input === 'undefined'){
throw new Error('Invalid argument');
}
asinc1(input, function(e, data){
if(err) return cb(e, null);
asinc2(data, function(e, result){
if(err) return cb(e, null);
return cb(null, result);
});
});
}
/* USAGE */
try{
myFunc(input, function(e, result){
if(err) // handle operational error.
else{
//continue what ever you need with result
}
})
}catch(e){
//crash gracefully
}
但是,如果我们以基于 promise 的方式编写这段代码:
function myFunc (input){
if(typeof input === 'undefined'){
throw new Error('Invalid argument');
}
return asinc1(input)
.then(asinc2);
}
/* USAGE */
myFunc(input)
.then(function(result){
//continue what ever you need with result
}).catch(function(e){
//handle both - programmatic and operational errors
})
没有办法区分错误类型,因此我不知道如果发生错误该怎么办。
最佳答案
我一直在做更多的研究并找到了两种可能的解决方案。然而,我对它们没有 100% 的把握,所以仍然很想听到其他答案或有人对我的方法发表评论。
有两种选择:
- 在创建时将错误对象标记为程序性或操作性。然后你可以将该对象冒泡到上层杠杆并在那里决定要做什么。
- 在上层杠杆(调用者)中实现两个捕获机制
为了实现第一个,我找到了两个好方法。一种是创建一个 custom MyError object ,第二个是简单地添加额外的标志:
if(programmatic error){
let e = new Error('Message');
e.isProgrammtic = true;
throw e;
}
现在您可以捕获它并传递给全局记录器对象,在该对象中进行简单检查是否是程序错误并采取相应措施。
第二个选项可以使用像 bluebird 这样的 promise 库。他们有 .error method捕获明确的操作错误。所以在我的示例中,我们可以这样做:
myFunc(input)
.then(function(result){
//continue what ever you need with result
}).catch(function(e){
//handle programatic errors. Crash gracefully and restart
}).error(function(e){
// handle operational error. Dont crash
})
关于javascript - 如何使用基于 promise 的 node.js 编码区分编程错误和操作错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45283235/