0

I'm new at using manyconsole and I have a question about handling user output. I have method which multiplies two numbers. And I want to print my own error messages when, for example, I didn't enter all parameters. Now program, as far as I understand, shows default error messages. How can I change that? This is my command class

class MultCommand : ConsoleCommand
{
    public int Argument1;
    public int Argument2;
    public int c;

    public MultCommand()
    {
        IsCommand("mult","multiply numbers");
        HasAdditionalArguments(2, "<Argument1> <Argument2>");
    }

    public override int Run(string[] remainingArguments)
    {
        if (remainingArguments == null || remainingArguments.Length == 0)
        {
            Console.WriteLine("You enter no numbers");
        }
        else
        {
            Argument1 = Convert.ToInt32(remainingArguments[0]);
            Argument2 = Convert.ToInt32(remainingArguments[1]);
            c = Argument1 * Argument2;
        }

        Console.WriteLine("Your answer is " + c.ToString());

        return 0;
    }
}

This is what I want You enter no numbers

This is what I get

Invalid number of arguments-- expected 2 more. 'mult' - multiply numbers Expected usage: Example.exe mult<Argument1> <Argument2>

John Saunders
  • 160,644
  • 26
  • 247
  • 397

2 Answers2

1

I think what you want is:

throw new ConsoleHelpAsException("You entered no numbers.");

After processing arguments and before executing Run() ManyConsole will print a summary of inputs (all public members of the command class, perhaps only those starting with capital letters I forget). So that your processing of remainingArguments is reflected in that summary, move that argument extraction to an override of OverrideAfterHandlingArgumentsBeforeRun:

public override int? OverrideAfterHandlingArgumentsBeforeRun (string[] remainingArguments)
{
    if (remainingArguments.Length != 2)
    {
        throw new ConsoleAsHelpException("You are expected to enter two numbers.");
    }
    else
    {
        Argument1 = Convert.ToInt32(remainingArguments[0]);
        Argument2 = Convert.ToInt32(remainingArguments[1]);
    }

    return base.OverrideAfterHandlingArgumentsBeforeRun (remainingArguments);
}

public override Run((string[] remainingArguments)
{
    c = Argument1 * Argument2;

    Console.WriteLine("Your answer is " + c.ToString());

    return 0;
}
Frank Schwieterman
  • 24,142
  • 15
  • 92
  • 130
1

Another approach is to override the CheckRequiredArguments method and throw there a new ConsoleHelpAsException with your custom message as exception's argument basing on the logic you want to get on passed args.

trix
  • 878
  • 6
  • 14