Configure default exception handler in a Service Fabric stateless service

207 Views Asked by At

I am trying to add a default exception handler for any unhandled exceptions in a stateless service, but it doesn't seem to be catching any of them. This is the code I am using:

protected override async Task RunAsync(CancellationToken cancellationToken)
{
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.HandleUnhandledExceptions);
    throw new Exception("This is an unhandled exception");
}

private void HandleUnhandledExceptions(object sender, UnhandledExceptionEventArgs args)
{
    Exception exception = (Exception)args.ExceptionObject;
    this.Logger.LogError("The application encountered unhandled exception: {exception}", exception.ToString());
}

I used AppDomain.CurrentDomain.UnhandledException before to add an exception handler, but in this case it doesn't seem to ever entering the handler method. I suspect it may be a thread or process related issue. Do you know why it doesn't work? Is there another way to set up an exception handler?

1

There are 1 best solutions below

0
LoekD On

Try this code, and run it without any debuggers attached to the process.

protected override async Task RunAsync(CancellationToken cancellationToken)
{
    AppDomain.CurrentDomain.UnhandledException += HandleUnhandledExceptions;
    TaskScheduler.UnobservedTaskException += HandleUnhandledTaskExceptions
    throw new Exception("This is an unhandled exception");
}

static void HandleUnhandledTaskExceptions(object sender, UnobservedTaskExceptionEventArgs e)
{
    Exception exception  = e.Exception;
    this.Logger.LogError("The application encountered unhandled task exception: {exception}", exception.ToString());
}

static void HandleUnhandledExceptions(object sender, UnhandledExceptionEventArgs e)
{
    Exception exception = (Exception)args.ExceptionObject;
    this.Logger.LogError("The application encountered unhandled exception: {exception}", exception.ToString());        }
}