在 Node 中,将错误参数传递给异步操作是一种约定:
async.someMagicalDust(function(callback) {
// some asynchronous task
// […]
callback();
}, function(err) {
// final callback
if(err) throw err;
// […]
});
也许我太天真了,但我从来都不是 if(variable)
表示法的忠实拥护者 — 可能是从 C 继承的,原因是 have already been discussed many times in the past .
另一方面,我有时会遇到一个null
参数和这个错误检查:
if(typeof err !== 'undefined' && err !== null)
有点太冗长了。
另一种解决方案是
if(err != null)
但我认为 non-strict check可能会很棘手,尽管我认为与 null 进行比较时这很正常。
在 Node 中检查错误参数的最佳方法是什么?
最佳答案
使用if(err)
。
它被设计成以这种方式使用。 Node 式回调应该仅在实际错误的情况下将错误设置为非假值。您找不到任何将 err
设置为 ''
或 0
来表示错误的合理示例。
就像 YlinaGreed 指出的那样,如果模块约定从 null
到 undefined
再到 0
甚至可能是 NaN
,你还是安全的。我从来没有被这个问题击中过,只使用了 if(err)
。
另一方面,您可能想使用 coffescript,它会为您翻译
unless err? then...
进入
if (typeof err === "undefined" || err === null) {
模仿最常见的模式。
一些链接证实了 if(err)
方法:
- https://gist.github.com/klovadis/2548942
- http://caolanmcmahon.com/posts/nodejs_style_and_structure/ (by Caolan McMahon,
async
作者) - http://thenodeway.io/posts/understanding-error-first-callbacks/
惯例似乎是传递一个错误对象作为第一个参数,null
表示没有错误,所以即使你传递一个空对象,它仍然是一个错误。
如果您使用流行的 express
框架,您应该使用 next
回调从中间件返回,它遵循 errback 约定。
我相信大多数人都喜欢比 next(null)
更简洁的 next()
,这意味着第一个参数的计算结果将是 undefined
而不是 null
,这当然是完全正常的用法。
关于node.js - 检查 Node 中的错误参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28107635/