Skip to content

Exception handling

Adam Bajguz edited this page Apr 5, 2021 · 4 revisions

Exception handling

By default all exceptions are handled using DefaultExceptionHandler class instance. However, it is possible to customize the behavior with a custom implementation of ICliExceptionHandler.

public class DefaultExceptionHandler : ICliExceptionHandler
{
    private readonly IConsole _console;
    private readonly IServiceProvider _serviceProvider;

    public DefaultExceptionHandler(IConsole console, IServiceProvider serviceProvider)
    {
        _console = console;
        _serviceProvider = serviceProvider;
    }

    public bool HandleException(Exception ex)
    {
        IConsole console = _console;

        switch (ex)
        {
            // Swallow directive exceptions and route them to the console
            case CommandException cx:
                {
                    WriteError(console, cx.Message);

                    if (cx.ShowHelp)
                    {
                        (_serviceProvider.GetService(typeof(IHelpWriter)) as IHelpWriter)?.Write();
                    }
                }
                return true;

            // Swallow command exceptions and route them to the console
            case DirectiveException dx:
                {
                    WriteError(console, dx.Message);

                    if (dx.ShowHelp)
                    {
                        (_serviceProvider.GetService(typeof(IHelpWriter)) as IHelpWriter)?.Write();
                    }
                }
                return true;

            // This may throw exceptions which are useful only to the end-user
            case TypinException tx:
                WriteError(console, tx.Message);

                return true;

            default:
                return false;
        }
    }

    private static void WriteError(IConsole console, string message)
    {
        console.Error.WithForegroundColor(ConsoleColor.Red, (error) => error.WriteLine(message));
        console.Error.WriteLine();
    }
}

To register the custom exception handler use:

    builder.UseExceptionHandler(new CustomExceptionHandler()))
    //or
    builder.UseExceptionHandler<CustomExceptionHandler>();
Clone this wiki locally