dotnet / dotnet/command-line-api
Make exception pretty listing public
- Dominant language
- C#
- Stars
- 3.7k
- Forks
- 428
- PR merge metrics
- No merged PRs in 30d
Description
It would be desirable for all flavors (previously referred to as app models) to use the same exception handling. Consistent display would be nice, but consistent cancellation handling seems the key thing.
You can predict that I will bring up the same issue for Help. I just do not yet have my head around those complexities.
If the local method `CommandLineBuilder UseExceptionHandle.Default` is moved to a public method, this consistency would be easy.
This needs a little discussion for two reasons:
* Where shoujld it go?
* Maybe a more consistent extension point - the code below instead of just the local function made public?
Making this an extension point would involve making lambda a public method. Something like:
```csharp
public void HandleException(Action? onException = null, Exception exception), InvocationContext context)
{
(onException ?? Default)(exception, context);
void Default(Exception exception, InvocationContext context)
{
if (exception is not OperationCanceledException)
{
context.Console.ResetTerminalForegroundColor();
context.Console.SetTerminalForegroundRed();
context.Console.Error.Write(context.LocalizationResources.ExceptionHandlerHeader());
context.Console.Error.WriteLine(exception.ToString());
context.Console.ResetTerminalForegroundColor();
}
context.ExitCode = errorExitCode ?? 1;
}
}
public static CommandLineBuilder UseExceptionHandler(
this CommandLineBuilder builder,
Action? onException = null,
int? errorExitCode = null)
{
builder.AddMiddleware(async (context, next) =>
{
try
{
await next(context);
}
catch (Exception exception)
{
HandleException(onException, exception, context);
}
}, MiddlewareOrderInternal.ExceptionHandler);
return builder;
}
```
@jonsequitur @baronfel @Keboo
Contributor guide
Assessment
This issue has not been assessed yet.