我遵循 Node JS 的空优先错误处理约定。回调以 callback(null, response)
的形式完成。收到回调响应后,是否每次都要检查error是否为null?
例子:
methodCB(function (error, response) {
if (error) {
//handle error
//Do i have to check this every single time for a callback?
//Are there design alternatives for this or is this just a node thing?
} else {
//process response
}
});
最佳答案
通常,错误可能是操作错误或程序员错误。
在处理和抛出这些错误之间做出选择是一个相当深入的话题。 node.js 中错误处理的规范指南是 Node.js Best Practice Exception Handling我强烈建议你阅读。 这篇文章强调了您应该专门处理错误的情况,以及您不应该处理的其他情况(相反,您要确保您的应用正常失败)。
无论错误的来源和处理/抛出的选择如何,正如 jfriend00 所建议的,所有健壮的代码都必须注意任何可能的错误返回。
关于javascript - 我是否必须在 nodejs 中的每个回调之后检查错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31365612/