Translate error codes to string to display

前端 未结 7 1270
无人共我
无人共我 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:38

    I wanted a way to have error code (int) and string description (any string) be declared in one and only one single place and none of the examples above allows that (ERR_OK has to be declared somewhere and then "ERR_OK" is mapped to it somewhere else).

    So I declared a simple class storing both int and string and maintaining a static map for int->string conversion. I also added an "auto-cast to" int function:

    class Error
    {
    public:
        Error( int _value, const std::string& _str )
        {
            value = _value;
            message = _str;
    #ifdef _DEBUG
            ErrorMap::iterator found = GetErrorMap().find( value );
            if ( found != GetErrorMap().end() )
                assert( found->second == message );
    #endif
            GetErrorMap()[value] = message;
        }
    
        // auto-cast Error to integer error code
        operator int() { return value; }
    
    private:
        int value;
        std::string message;
    
        typedef std::map 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;
            }
        }
    };
    

    Then, you simply declare your error codes as below:

    static Error ERROR_SUCCESS(                 0, "The operation succeeded" );
    static Error ERROR_SYSTEM_NOT_INITIALIZED(  1, "System is not initialised yet" );
    static Error ERROR_INTERNAL(                2, "Internal error" );
    static Error ERROR_NOT_IMPLEMENTED(         3, "Function not implemented yet" );
    

    Then, any function returning int can do to return 1

    return ERROR_SYSTEM_NOT_INITIALIZED;
    

    And, client programs of your library will get "System is not initialised yet" when calling

    Error::GetErrorString( 1 );
    

    The only limitation I see is that static Error objects are created many times if .h file declaring them is included by many .cpp (that's why I do a _DEBUG test in constructor to check consistency of the map). If you don't have thousands of error code, it should be a problem (and there may be a workaround...)

    Jean

提交回复
热议问题