CLI11 icon indicating copy to clipboard operation
CLI11 copied to clipboard

Ability to modify exception messages

Open levi-de-koning opened this issue 1 year ago • 1 comments

We are using CLI11 for an app. We have done a lot of tinkering with the output. One of the things we ran into during this was the lack of control for the formatting of exceptions. A lot of my problems are similar to the problems mentioned in issue 167

Take the following code in app.cpp:

    if(min_num > collected) {  // if we have run out of arguments and the minimum was not met
        throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
    }
    CLI11_ERROR_DEF(ParseError, ArgumentMismatch)
    CLI11_ERROR_SIMPLE(ArgumentMismatch)
    ArgumentMismatch(std::string name, int expected, std::size_t received)
        : ArgumentMismatch(expected > 0 ? ("Expected exactly " + std::to_string(expected) + " arguments to " + name +
                                           ", got " + std::to_string(received))
                                        : ("Expected at least " + std::to_string(-expected) + " arguments to " + name +
                                           ", got " + std::to_string(received)),
                           ExitCodes::ArgumentMismatch) {}

    static ArgumentMismatch AtLeast(std::string name, int num, std::size_t received) {
        return ArgumentMismatch(name + ": At least " + std::to_string(num) + " required but received " +
                                std::to_string(received));
    }

As you can see here, the entire context is essentially lost as everything is combined into a string, making it incredibly difficult to modify this at a later stage.

So, for me, the solution would be either what is mentioned in the original issue and store information in the exception about the context, or what I think would be even better is to allow the user, like for many other things, to specify a callback for these default build in errors. So, the user gets the ability to build the desired output format.

levi-de-koning avatar Jan 22 '24 17:01 levi-de-koning

That is kind of an interesting idea (exception callbacks), Might explore that a bit further once we get the upcoming release out.

phlptp avatar Jan 23 '24 22:01 phlptp