【发布时间】:2015-11-05 23:07:41
【问题描述】:
我正在使用 node.js 中的 Promises(使用 Q 库)。我已将所有基于回调的代码移植到 Promises,一切似乎都很好。但是,我似乎一直在实施一种我觉得可疑的模式。我觉得可能有更好的方法来处理这个问题,但我不确定是什么。
基本上,如果您有可能从异步操作中获取错误,并且您可能能够也可能无法在本地处理它。例如,处理某一类错误,并传播其余的错误。在基于回调的代码中,我会这样做:
fs.readFile(path, 'utf-8', function (err, data) {
if(err) {
if(err.code == "ENOENT") {
cb(null, null); //it's fine to return null and eat the error
} else {
cb(err, null); //this is probably not fine, so barf
}
return;
}
...
});
在基于 Promise 的代码中,这变成:
return fs.readFile(path, 'utf-8').then( function(data) { ... }, function(err) {
if(err.code == "ENOENT") {
return null; //it's fine to return null and eat the error
}
throw err; //this is probably not fine, so barf
});
我不喜欢的部分是重新抛出错误。我来自 .NET 背景,因此重新抛出这样的异常基本上是一种可激发的攻击。但是,也许在 JavaScript 中这无关紧要?或者,有没有办法写这个我不知道的代码?
【问题讨论】:
-
.NET 中为什么是
a fireable offense to rethrow an exception like this? -
因为这会破坏原始堆栈跟踪,因为它设置在
throw,而不是new -
我不喜欢承认 Java 优于 C#,但是当 Tomcat 中发生异常时,如果异常有 getCause() 条目,它会显示第二/第三个堆栈跟踪。
标签: javascript node.js promise q