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?
Try this code, and run it without any debuggers attached to the process.