Jeff
Jeff

Reputation: 36583

System.CommandLine Exception Handling

Is there any documentation on best practices for exception handling with System.CommandLine?

I build a handler via CommandHandler.Create and return the result of InvokeAsync from my console application.

What should I do about reporting exceptions to the user of my app? If I try/catch/log inside my handler and set Environment.ExitCode, it gets ignored of course, because I'm returning the result of InvokeAsync and my handler doesn't return anything but a task.

What is the recommended pattern for returning non-zero exit codes?

Upvotes: 6

Views: 2787

Answers (1)

Sir Rufo
Sir Rufo

Reputation: 19106

The CommandHandler.Create method has some overloads where you can return an int which is used as the ExitCode

public static class CommandHandler
{
    ...
    public static ICommandHandler Create(Func<int> action) =>
        HandlerDescriptor.FromDelegate(action).GetCommandHandler();

    public static ICommandHandler Create<T>(
        Func<T, int> action) =>
        HandlerDescriptor.FromDelegate(action).GetCommandHandler();
    ...
}

https://github.com/dotnet/command-line-api/blob/master/src/System.CommandLine/Invocation/CommandHandler.cs

Upvotes: 3

Related Questions