Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions src/System.CommandLine.Tests/UseExceptionHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,23 @@ public async Task UseExceptionHandler_catches_command_handler_exceptions_and_wri
error.ToString().Should().Contain("System.Exception: oops!");
}

[Fact]
public async Task When_thrown_exception_is_from_cancelation_no_output_is_generated()
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task UseExceptionHandler_writes_cancellation_exception_details_to_standard_error(bool taskCanceled)
{
Command command = new("the-command");
command.SetAction((_, __) => throw new OperationCanceledException());
Exception exception = taskCanceled
? new TaskCanceledException("task canceled")
: new OperationCanceledException("operation canceled");
command.SetAction((_, __) => throw exception);

var output = new StringWriter();
var error = new StringWriter();

int resultCode = await command.Parse("the-command").InvokeAsync(new() { Output = output, Error = error }, CancellationToken.None);
int resultCode = await command.Parse("the-command").InvokeAsync(new() { Error = error }, CancellationToken.None);

output.ToString().Should().BeEmpty();
resultCode.Should().NotBe(0);
error.ToString().Should().Contain(exception.ToString());
resultCode.Should().Be(1);
}

[Theory]
Expand Down
15 changes: 6 additions & 9 deletions src/System.CommandLine/Invocation/InvocationPipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,18 +138,15 @@ internal static int Invoke(ParseResult parseResult)

private static int DefaultExceptionHandler(Exception exception, ParseResult parseResult)
{
if (exception is not OperationCanceledException)
{
ConsoleHelpers.ResetTerminalForegroundColor();
ConsoleHelpers.SetTerminalForegroundRed();
ConsoleHelpers.ResetTerminalForegroundColor();
ConsoleHelpers.SetTerminalForegroundRed();

var error = parseResult.InvocationConfiguration.Error;
var error = parseResult.InvocationConfiguration.Error;

error.Write(LocalizationResources.ExceptionHandlerHeader());
error.WriteLine(exception.ToString());
error.Write(LocalizationResources.ExceptionHandlerHeader());
error.WriteLine(exception.ToString());

ConsoleHelpers.ResetTerminalForegroundColor();
}
ConsoleHelpers.ResetTerminalForegroundColor();
return 1;
}

Expand Down