C++ 来自API的错误代码。。。好的做法是什么
我正在使用专有API编写主机应用程序。 当发生错误时,此API返回错误代码。 我需要您的建议,告诉我在我的主机应用程序中推送错误代码并管理它们的最佳方法: 这里有一个简短的例子: CCas.cppC++ 来自API的错误代码。。。好的做法是什么,c++,C++,我正在使用专有API编写主机应用程序。 当发生错误时,此API返回错误代码。 我需要您的建议,告诉我在我的主机应用程序中推送错误代码并管理它们的最佳方法: 这里有一个简短的例子: CCas.cpp CMD_STATUS CCas::shutdown() const { /* CMD_STATUS_OK is an API return code */ uint8_t statusByte = CMD_STATUS_OK; /* Shutdown the CAS
CMD_STATUS CCas::shutdown() const
{
/* CMD_STATUS_OK is an API return code */
uint8_t statusByte = CMD_STATUS_OK;
/* Shutdown the CAS system */
if (CMD_STATUS_OK != (statusByte = CAS_Master_ShutDown()))
return statusByte;
/* Set nReset to HIGH */
...
...
/* Done the system is OFF */
return statusByte;
}
int main(char *argc, char **argv)
{
CMD_STATUS retByte = CMD_STATUS_OK;
CCas vmx;
if(retByte != vmx.shutdown())
/* Something wrong happened */
return retByte;
return 0
}
main.cpp
CMD_STATUS CCas::shutdown() const
{
/* CMD_STATUS_OK is an API return code */
uint8_t statusByte = CMD_STATUS_OK;
/* Shutdown the CAS system */
if (CMD_STATUS_OK != (statusByte = CAS_Master_ShutDown()))
return statusByte;
/* Set nReset to HIGH */
...
...
/* Done the system is OFF */
return statusByte;
}
int main(char *argc, char **argv)
{
CMD_STATUS retByte = CMD_STATUS_OK;
CCas vmx;
if(retByte != vmx.shutdown())
/* Something wrong happened */
return retByte;
return 0
}
在我的示例中,在方法shutdown中,当出现错误时,我将statusByte变量中的错误推送到main,在main中,我捕获错误并停止程序
我是用正确的方式使用它,还是有其他的方法。
我是否需要在main中创建自己的错误代码
请你给个建议
谢谢这里没有明确的答案,也没有一种方法是最终的黄金方法。
无论你做什么,我都会说——保持一致。
如果您正在编写C++代码,那么您应该考虑使用异常而不是错误代码。 异常有助于轻松编写主机代码,并有助于打破主代码中的错误处理逻辑:
try {
apiCall();
anotherApiCall();
yetAnotherApiCall();
} catch (someKindOfError){
// Handle error here
} catch (anotherKindOfError){
// Handle other errors here
} catch (baseError){
// A more generic error handling here
} catch (...){
// Just make sure you don't catch what you can't handle and leave higher layers handle it
}
另一种方法是使用错误代码,代码被破坏,如果这个那么那个,但这是一种有效的方法,但不是更少。
在本例中,我将形成一个常数,表示成功(如posix 0),然后类似于:
ErrorType retVal = someApiCall();
if (retVal != ErrorCodeSuccess){
// either handle generic error or try to find out if it's a specific error, etc.
if (retVal == ErrorCodeCatIsHungry){
// Handle error here and probably bail out by calling 'return retVal;'
}
}
有些人使用返回失败代码的方法(void
函数返回布尔值,返回对象的函数返回null
或静态标志对象表示错误),然后根据请求调用更详细的错误函数:getLastErrorOfMyLovelyApi()
这不是我个人的喜好,但有时在C API中很有用,因为错误可能是一组复杂的信息。
这一切都取决于你的受众是谁,你为他们提供了什么工具(C++有例外,C没有),以及你的个人品味。
如果你问我,异常(即使只是来自stdexcept
的标准异常)是你的解决方案。启动异常如何?如果出现问题,你的main
函数将返回CMD\u STATUS\u OK,这是预期的吗?这是异常的典型用例,为什么不使用它们?你真的应该看看这个C++常见问题,特别是如果你来自C世界:-你不会花太长时间阅读,但最有可能提供巨大的洞察力。在你的例子中,由于API使用错误代码,我将把它们包装在异常中。这个问题没有一个真正的单一答案。您可以包装错误,可以抛出异常,或者只是传播底层错误。所有这三种选择都同样有效。不过,请注意例外情况:虽然使用它们似乎很有诱惑力,但它们应该为真正的例外问题保留。