我正在使用专有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 system */
if (CMD_STATUS_OK != (statusByte = CAS_Master_ShutDown()))
return statusByte;
/* Set nReset to HIGH */
...
...
/* Done the system is OFF */
return statusByte;
}
main.cpp
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
}
在我的示例中,在引发错误的方法关闭内部,我将statusByte变量内的错误上推至主体,在主体内我捕获了该错误并停止了程序。
我以正确的方式使用它还是有另一种方法可以使用?
我是否需要在主目录中创建自己的错误代码。
请您指教。
谢谢
最佳答案
这里没有确定的答案,也没有单一的方法可以作为最终的黄金方法。
无论您做什么,我都会说-保持一致。
如果要编写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
}
另一种方法是使用错误代码,该代码会被
if this
破坏then that
,但这仍然是一种有效的方法。在这种情况下,我将形成一个表示成功的常量(例如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
函数返回 bool(boolean) 值,返回对象的函数返回null
或表示错误的静态标志对象),然后根据请求调用更详细的错误函数:getLastErrorOfMyLovelyApi()
。这不是我的个人喜好,但有时在C API中很有用,因为其中的错误可能是一组复杂的信息。
这一切都取决于您的受众是谁,为他们提供哪些工具(C++有异常(exception),C没有)以及您的个人喜好。
如果您问我,异常(exception)(甚至只是
stdexcept
中的标准异常(exception))就是解决您的问题的方法。关于c++ - API中的错误代码...有什么好的做法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58554740/