dotnet / dotnet/command-line-api

Gracefully handle exceptions in command handlers

Abierto
#1,655 5 comentarios 0 reacciones 0 asignados Ver en GitHub
Lenguaje dominante
C#
Estrellas
3.7k
Forks
428
Métricas de merge de PR
Sin PR fusionados en 30 d

Descripción

When an exception occurs in a command handler the entire stack trace is barfed out into stderr and I'd like to not have that behavior for explicitly handled exceptions. Consider a handler that tries to read a file but the filename is not found. The standard libraries throw a FileNotFoundException which I'd like to catch and display just the message and not the entire stack trace. For unhandled exceptions I think the current behavior of the stack trace is fine since by definition it is unhandled.

I looks like I can get the invocation context and set the invocation result to a custom IInvocationResult. The problem is there doesn't appear to be (or I missed it 😅) an ErrorResult for setting a user-defined error that the handler failed. I made my own that is essentially a copy of `ParseErrorResult` but you can specify the message in the ctor.

```c#
public class ErrorResult : IInvocationResult
{
private readonly string _errorMessage;
private readonly int _errorExitCode;

public ErrorResult(string errorMessage, int errorExitCode = 1)
{
_errorMessage = errorMessage;
_errorExitCode = errorExitCode;
}

public void Apply(InvocationContext context)
{
context.Console.ResetTerminalForegroundColor();
context.Console.SetTerminalForegroundRed();

context.Console.Error.WriteLine(_errorMessage);
context.Console.Error.WriteLine();

context.ExitCode = _errorExitCode;

context.Console.ResetTerminalForegroundColor();
}
}
```

The main issue I ran into was that `ResetTerminalForegroundColor` and `ResetTerminalForegroundColor` are internal extension methods and those also rely on the internal `Platform` static class. I copied them into my code base for now.

Assuming those APIs were public, ErrorResult now works and you can use it like in the following trivial example:

```c#
void Handler(InvocationContext ctx, string filename)
{
try
{
Console.WriteLine(File.ReadAllText(filename));
}
catch (FileNotFoundException e)
{
ctx.InvocationResult = new ErrorResult(e.Message, 42);
}
}
```

Now when the handled exception occurs, it doesnt bubble up and kill the application but instead just prints (in red) to stderr.

I'm not familiar with the details of how System.CommandLine works. Do you think this is a valid approach for handling exceptions in a handler?

Guía de contribución

Abrir la guía de contribución

Línea de trabajo

Comienza leyendo la ruta de resultados de invocación alrededor de InvocationContext, IInvocationResult y ParseErrorResult; después, inspecciona los métodos internos de color del terminal y la dependencia Platform mencionados en el issue. El trabajo estará completo cuando el enfoque admitido por el proyecto para las excepciones controladas y no controladas, la salida de stderr y los códigos de salida esté claramente definido y validado.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
csharp
Área
cli
Tipo de issue
Nueva funcionalidad
Dificultad
5/5
Tiempo estimado
Más de una semana
Estado de actividad
Estancado
Claridad
Necesita aclaración
Aptitud para principiantes
30/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.