Error handling design: Bind error messages to error codes

Viewed 121

I have a simple structures to handle errors

enum class Error
{
    None = 0,
    FirstError,
    SecondError,
    ThirdError,
    ...
}

struct ErrorCategory
{
    static const std::string& Message(Error aError)
    {

        static const std::string messages[] =
        {
            "first error message",
            "second error message",
            "third error message",
            ...
        }

        const auto index = static_cast<size_t>(aError);
        assert(index < std::size(messages) && "Invalid error");
        return messages[index];
    }
};

Also, there are some class and methods to work with those structures.

Though it works, but the amount of errors is growing, so it becomes hard to navigate between error messages and error codes in enum. I want to declare error code and message for it in one place to make it easy to find error code. Is there a way to do it without making my code huge (such as enum + switch cases for messages) so it would be easy to maintain and without using macro?

2 Answers

You can use std::map<Error, std::string> like:

enum class Error : uint8_t {
    None        = 0,
    FirstError  = 1,
    SecondError = 2,
    ThirdError  = 3
};

std::map<Error, std::string> error_messages = {
    { Error::None,        "unknown error message" },
    { Error::FirstError,  "first error message"   },
    { Error::SecondError, "second error message"  },
    { Error::ThirdError,  "third error message"   }
};

and then use it afterwards like:

std::cerr << error_messages[Error::None]        << std::endl;
std::cerr << error_messages[Error::FirstError]  << std::endl;
std::cerr << error_messages[Error::SecondError] << std::endl;
std::cerr << error_messages[Error::ThirdError]  << std::endl;

Demo

This type of operation is exactly how most localized UIs work. You map some common structured ID to a user-facing string.

Because of this, there are a huge amount of platform-specific ways of doing this which aim to do exactly what you want. For example on Windows:

Related