Skip to content

Instantly share code, notes, and snippets.

@jasper-d
Created June 30, 2023 09:08
Show Gist options
  • Save jasper-d/e08f7123c8050d1a738793858aa934f3 to your computer and use it in GitHub Desktop.
Save jasper-d/e08f7123c8050d1a738793858aa934f3 to your computer and use it in GitHub Desktop.
Non-zero exit code
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
internal static class Program
{
public static async Task Main()
{
await new HostBuilder()
.ConfigureServices(cfg => cfg.AddHostedService<ErrorBackgroundService>())
.RunConsoleAsync();
}
internal sealed class ErrorBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Yield here, because synchronously throwing ExecuteAsync calls
// are handled by the host.
await Task.Yield();
try
{
Throw();
}
catch (OperationCanceledException oce) when (oce.CancellationToken == stoppingToken)
{
// This is fine, we threw because an operation got cancelled
// because of shutdown.
}
}
private void Throw()
{
throw new InvalidOperationException("This is deliberate");
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
if (ExecuteTask?.IsFaulted == true && ExecuteTask.Exception is AggregateException aex)
{
// Throwing here is crucial to get a non-zero exit code
throw new AggregateException($"{nameof(ErrorBackgroundService)} in fatal state", aex.InnerExceptions);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment