Translate error codes to string to display

前端 未结 7 1367
无人共我
无人共我 2021-01-03 03:18

Is there a common way in C++ to translate an error code to a string to display it?

I saw somewhere a err2msg function, with a big switch, but is that re

7条回答
  •  被撕碎了的回忆
    2021-01-03 03:37

    As far as I am concerned, error codes are just a subset of enums. Since we are not blessed in C++ with pretty enums (which makes logs somehow quite hard to parse), error codes are no more easier.

    The solution is pretty simple for error codes though:

    class ErrorCode
    {
    public:
      ErrorCode(): message(0) {}
      explicit ErrorCode(char const* m): message(m) {}
    
      char const* c_str() const { return message; }
      std::string toString() const
      {
        return message ? std::string(message) : std::string();
      }
    
    private:
      char const* message;
    };
    
    std::ostream& operator<<(std::ostream& out, ErrorCode const& ec)
    {
      return out << ec.c_str();
    }
    

    Of course you can supply the traditional ==, !=, <, etc...

    • It's simple!
    • It's fast (the code IS the string, no look-up involved)
    • It's type safe (you cannot accidentally mix it up with another type)

    The idea is to return pointers to the text instead of error codes (though wrapped in a class for type safety).

    Usage:

    // someErrors.h
    extern ErrorCode const ErrorOutOfMemory;
    
    // someErrors.cpp
    ErrorCode const ErrorOutOfMemory = ErrorCode("OUT OF MEMORY");
    

提交回复
热议问题