我是否必须在 nodejs 中的每个回调之后检查错误?
Do I have to check for error after every callback in nodejs?
我遵循 Node JS 的 null 第一个错误处理约定。回调完成为 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,我强烈建议您阅读。
本文强调了您应该专门处理错误的情况,以及您不应该处理的其他情况(相反,您要确保您的应用正常失败)。
无论错误的来源和handling/throwing的选择如何,正如jfriend00所建议的,所有健壮的代码都必须注意任何可能的错误return.
我遵循 Node JS 的 null 第一个错误处理约定。回调完成为 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,我强烈建议您阅读。 本文强调了您应该专门处理错误的情况,以及您不应该处理的其他情况(相反,您要确保您的应用正常失败)。
无论错误的来源和handling/throwing的选择如何,正如jfriend00所建议的,所有健壮的代码都必须注意任何可能的错误return.