2

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?

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Though I still have to declare enum and map, which looks quite huge for big amount of errors
@Cmanfred IMHO well if you have large amount of errors, you can't escape from writing an error message and/or error code for each of them. That's the cost you need to take.
0

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.