在进行程序设计时,有时候需要设计自定义的错误代码和错误信息,以方便追踪程序发生错误的位置和错误信息。
1 错误代码定义
/**
* Error.h
* @brief define error code.
*/
typedef enum class ErrorCodeType : long {
OK = 0, ///< OK
NO_CAMERA_CONNECTED = 0x800E0001, ///< No camera connected to system.
} ErrorCode;
2 获取错误消息
/**
* Error.h
*/
#include<map>
class Error {
public:
static const char * getErrorMsg(ErrorCode errorCode, const char *fmt="", ...);
private:
static std::map<ErrorCode, const char *> ERROR_MSG;
};
/**
* Error.cpp
*/
#include "Error.h"
#include <cstdarg>
#include <cstring>
std::map<ErrorCode, const char *> Error::ERROR_MSG = {
{ErrorCode::OK, "Success."},
{ErrorCode ::NO_CAMERA_CONNECTED, "No camera connected to system."}
};
const char *Error::getErrorMsg(ErrorCode errorCode, const char *fmt, ...) {
char errorCodeStr[32];
sprintf(errorCodeStr, "Code: 0x%8lX", static_cast<long>(errorCode));
va_list al;
va_start(al, fmt);
char buffer[1024];
memset(buffer, 0, 1024);
vsnprintf(buffer, 1024, fmt, al);
std::string msg = (std::string(errorCodeStr) + " Msg: " + ERROR_MSG[errorCode] + " \"" + std::string(buffer)) + "\"";
static char message[1024];
strcpy(message, errorCodeStr);
strcat(message, " Msg: ");
strcat(message, ERROR_MSG[errorCode]);
if (strlen(buffer) != 0) {
strcat(message, " \"");
strcat(message, buffer);
strcat(message, "\"");
}
return message;
}
3 测试
/**
* test.cpp
*/
#include "Error.h"
#include <iostream>
int main(int argc, char** argv) {
ErrorCode ret = ErrorCode::NO_CAMERA_CONNECTED;
std::cout << "Error Message: " << Error::getErrorMsg(ret, "test Error class");
return 0;
}