标签 错误码 下的文章

C++: 自定义错误码类,实现归拢错误信息。


需求

求解器老报错,还得找错误在哪,其实大多数都是一些属性没配置才导致报错,在报错的地方throw出来就能知道具体是哪些错误,把错误编码,这样就能把类似宏这种的返回编码,然后根据编码能查到具体错误信息。

用法

  • // 定义相关错误
  • static Error E_NOT_FOUND_PTR(100010001,"未发现指针");
  • // 响应相关错误
  • throw E_NOT_FOUND_PTR;
  • // 查询相关错误并输出
  • try{
  • // 生产代码
  • } catch (Error info) {
  • cout << "[ERROR] [" << info << "] [" << Error::GetErrorString(info) << "]" << endl;
  • }

类代码

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