【问题标题】:Configure default exception handler in a Service Fabric stateless service在 Service Fabric 无状态服务中配置默认​​异常处理程序
【发布时间】:2021-08-20 03:38:29
【问题描述】:

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

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 添加异常处理程序,但在这种情况下,它似乎从未进入处理程序方法。我怀疑这可能是线程或进程相关的问题。你知道为什么它不起作用吗?还有其他方法可以设置异常处理程序吗?

【问题讨论】:

    标签: .net azure-service-fabric appdomain unhandled-exception service-fabric-stateless


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2021-02-01
      • 1970-01-01
      • 2017-07-26
      • 2016-11-16
      • 2017-02-18
      • 2017-09-18
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多