Skip to content

Commit c25f85b

Browse files
authored
Skipping output when exception is from cancellation (#1132)
* Skipping output when exception is from cancellation
1 parent c728207 commit c25f85b

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/System.CommandLine.Tests/UseExceptionHandlerTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,20 @@ public async Task Declaration_of_UseExceptionHandler_can_come_before_other_middl
109109
.Contain("oops!");
110110
}
111111

112+
[Fact]
113+
public async Task When_thrown_exception_is_from_cancelation_no_output_is_generated()
114+
{
115+
int resultCode = await new CommandLineBuilder()
116+
.AddCommand(new Command("the-command"))
117+
.UseExceptionHandler()
118+
.UseMiddleware(_ => throw new OperationCanceledException())
119+
.Build()
120+
.InvokeAsync("the-command", _console);
121+
122+
_console.Out.ToString().Should().BeEmpty();
123+
resultCode.Should().NotBe(0);
124+
}
125+
112126
[Fact]
113127
public async Task UseExceptionHandler_output_can_be_customized()
114128
{

src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -290,14 +290,16 @@ public static CommandLineBuilder UseExceptionHandler(
290290

291291
void Default(Exception exception, InvocationContext context)
292292
{
293-
context.Console.ResetTerminalForegroundColor();
294-
context.Console.SetTerminalForegroundRed();
295-
296-
context.Console.Error.Write("Unhandled exception: ");
297-
context.Console.Error.WriteLine(exception.ToString());
293+
if (!(exception is OperationCanceledException))
294+
{
295+
context.Console.ResetTerminalForegroundColor();
296+
context.Console.SetTerminalForegroundRed();
298297

299-
context.Console.ResetTerminalForegroundColor();
298+
context.Console.Error.Write("Unhandled exception: ");
299+
context.Console.Error.WriteLine(exception.ToString());
300300

301+
context.Console.ResetTerminalForegroundColor();
302+
}
301303
context.ResultCode = 1;
302304
}
303305
}

0 commit comments

Comments
 (0)