C++定义错误码类

我们平时有这样的需求,可能是C用户的老习惯了,在底层的组件中更喜欢用返回错误码的形式来告知用户函数的调用状态,一般来说,简单用#define 一个宏来包装下返回值。

#define ERR_SYSTEM_INIT -23 // system initailized fail

比如,以上定义了一个错误码返回-23,意味着系统初始化失败。但是宏包含的信息太少,有些时候,用户不能如人意的理解错误原因。必须给这错误加以说明。所以就索性写了一个Error类可以定义错误码和相关错误信息,并通过错误码返回更详细的说明:

 1 #include <string>
 2 #include <map>
 3 #include <cassert>
 4 
 5 class Error
 6 {
 7 public:
 8 Error(int value, const std::string& str)
 9 {
10 m_value = value;
11 m_message =    str;
12 #ifdef _DEBUG
13 ErrorMap::iterator found = GetErrorMap().find(value);
14 if (found != GetErrorMap().end())
15 assert(found->second == m_message);
16 #endif
17 GetErrorMap()[m_value] = m_message;
18 }
19 
20 // auto-cast Error to integer error code
21 operator int() { return m_value; }
22 
23 private:
24 int m_value;
25 std::string m_message;
26 
27 typedef std::map<int, std::string> ErrorMap;
28 static ErrorMap& GetErrorMap()
29 {
30 static ErrorMap errMap;
31 return errMap;
32 }
33 
34 public:
35 
36 static std::string GetErrorString(int value)
37 {
38 ErrorMap::iterator found = GetErrorMap().find(value);
39 if (found == GetErrorMap().end())
40 {
41 assert(false);
42 return "";
43 }
44 else
45 {
46 return found->second;
47 }
48 }
49 };
50 
51  
View Code

以下是用法:

#define ERR_SYSTEM_INIT -23 //system initailized fail 改成 static Error SYSTEM_NOT_INIT(-23,"system initailized fail");


函数里面返回错误码,这样返回:

int foo()
{
return SYSTEM_NOT_INIT;
}

然后用户想通过返回值得到更详细的信息时,可以这样做:

cout << Error::GetErrorString(err_code) << std::endl;

原文地址:https://www.cnblogs.com/foohack/p/4949614.html