簡體   English   中英

在 Service Fabric 無狀態服務中配置默認異常處理程序

[英]Configure default exception handler in a Service Fabric stateless service

我正在嘗試為無狀態服務中的任何未處理異常添加默認異常處理程序,但它似乎沒有捕獲其中任何一個。 這是我正在使用的代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM