在 Service Fabric 无状态服务中配置默认​​异常处理程序

问题描述

我正在尝试为无状态服务中的任何未处理异常添加认异常处理程序,但它似乎没有捕获任何异常。这是我正在使用的代码

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());
}

我之前使用 AppDomain.CurrentDomain.UnhandledException 添加异常处理程序,但在这种情况下,它似乎从未进入处理程序方法。我怀疑这可能是线程或进程相关的问题。你知道为什么它不起作用吗?还有其他方法可以设置异常处理程序吗?

解决方法

试试这个代码,并在没有任何调试器附加到进程的情况下运行它。

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());        }
}