C++定义错误码类

2021/6/29 20:23:54

本文主要是介绍C++定义错误码类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

#define ERR_SYSTEM_INIT -23 // system initailized fail

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

#include <string>
 #include <map>
 #include <cassert>
 
 class Error
 {
 public:
 Error(int value, const std::string& str)
 {
 m_value = value;
 m_message =    str;
 #ifdef _DEBUG
 ErrorMap::iterator found = GetErrorMap().find(value);
 if (found != GetErrorMap().end())
 assert(found->second == m_message);
 #endif
 GetErrorMap()[m_value] = m_message;
 }
 
 // auto-cast Error to integer error code
 operator int() { return m_value; }
 
 private:
 int m_value;
 std::string m_message;
 
 typedef std::map<int, std::string> ErrorMap;
 static ErrorMap& GetErrorMap()
 {
 static ErrorMap errMap;
 return errMap;
 }
 
 public:
 
 static std::string GetErrorString(int value)
 {
 ErrorMap::iterator found = GetErrorMap().find(value);
 if (found == GetErrorMap().end())
 {
 assert(false);
 return "";
 }
 else
 {
 return found->second;
 }
 }
 };

以下是用法:

#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;



这篇关于C++定义错误码类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程