Skip to content

Commit

Permalink
Extensions: don't swallow exceptions
Browse files Browse the repository at this point in the history
I was tricked into thinking un-handled exceptions didn't result in a
non-zero exit code because of a Visual Studio debugger quirk. The
debugger's console window says "exited with code 0," but it lies!

UseExceptionHandler() is available for consumers who want to avoid hard
crashes.

fixes #5
  • Loading branch information
wjrogers committed Jun 22, 2023
1 parent 4490c87 commit 130b5fd
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 26 deletions.
24 changes: 3 additions & 21 deletions XO.Console.Cli.Extensions/CommandAppHostBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,18 +73,10 @@ internal static async Task<int> RunCommandAppAsync(
hostBuilder.ConfigureServices(
(_, services) => services.AddCommandApp(builderFactory, configure));

IHost host;
try
{
host = hostBuilder.Build();
}
catch (Exception ex)
{
System.Console.Error.WriteLine(ex.Message);
return -1;
}
// build the host
using var host = hostBuilder.Build();

// get a reference to the logger factory
// get a reference to the logger factory so we can dispose it last
var loggerFactory = host.Services.GetService<ILoggerFactory>();

// run the host
Expand All @@ -94,11 +86,6 @@ internal static async Task<int> RunCommandAppAsync(
result = await host.RunCommandAppAsync(args)
.ConfigureAwait(false);
}
catch (Exception ex)
{
System.Console.Error.WriteLine(ex.Message);
result = -1;
}
finally
{
await DisposeAndFlush(host, loggerFactory)
Expand All @@ -118,11 +105,6 @@ private static ValueTask DisposeAndFlush(IHost host, ILoggerFactory? loggerFacto
host.Dispose();
return ValueTask.CompletedTask;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
return ValueTask.CompletedTask;
}
finally
{
loggerFactory?.Dispose();
Expand Down
7 changes: 2 additions & 5 deletions XO.Console.Cli.Extensions/CommandAppHostExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,14 @@ public static async Task<int> RunCommandAppAsync(this IHost host, IReadOnlyList<
try
{
logger?.LogDebug("Executing command {Command} ... ", from x in parse.GetVerbs() select x.Value);
logger?.LogTrace("Command args: {Args}", args);

result = await app.ExecuteAsync(parse, lifetime.ApplicationStopping)
.ConfigureAwait(false);
}
catch (Exception ex)
{
logger?.LogCritical(ex, "Unhandled exception: {ExceptionMessage}", ex.Message);

System.Console.Error.WriteLine(ex.Message);
result = 1;
logger?.LogCritical(ex, "An unhandled exception occurred while executing the command.");
throw;
}
finally
{
Expand Down

0 comments on commit 130b5fd

Please sign in to comment.