发生异常时整个 Blazor Web 应用停止工作

Whole blazor web app stop working when exception occured

请为我提出以下问题的任何合适的解决方案,

当 blazor 应用程序抛出任何异常时,整个应用程序都会停止运行并且 link 无法正常工作,直到我可以再次通过工作室 运行 应用程序。

如何处理这个问题?

谢谢并致以最诚挚的问候

已编辑

(为了提供请求的信息)

重现步骤:

  1. 创建 blazorserverside 应用程序:

  2. 修改增量计数

Counter.razor

void IncrementCount()
{
    currentCount += 1;
    _ = 0 / (5-currentCount);  // <-- force error when currentCount is 5.
}
  1. Click Me 按钮 5 次以引发错误。

  2. 尝试导航到其他应用程序页面(主页、获取数据)没有任何反应,因为它在客户端静默失败。

附加信息

On Startup.cs 配置错误:

app.UseExceptionHandler("/errors");

堆栈跟踪错误:

Unhandled exception rendering component: Attempted to divide by zero.
System.DivideByZeroException: Attempted to divide by zero.
   at blaex.Pages.Counter.IncrementCount() in /home/dani/tmp/blaex/Pages/Counter.razor:line 27
   at Microsoft.AspNetCore.Components.EventCallbackWorkItem.InvokeAsync[T](MulticastDelegate delegate, T arg)
   at Microsoft.AspNetCore.Components.ComponentBase.Microsoft.AspNetCore.Components.IHandleEvent.HandleEventAsync(EventCallbackWorkItem callback, Object arg)
   at Microsoft.AspNetCore.Components.Rendering.Renderer.DispatchEventAsync(Int32 eventHandlerId, UIEventArgs eventArgs)

2021 年 7 月编辑

幸运的是,我们现在有这方面的官方文献:Handle errors in ASP.NET Core Blazor apps :

When a Blazor app isn't functioning properly during development, receiving detailed error information from the app assists in troubleshooting and fixing the issue. When an error occurs, Blazor apps display a light yellow bar at the bottom of the screen:

  • During development, the bar directs you to the browser console, where you can see the exception.
  • In production, the bar notifies the user that an error has occurred and recommends refreshing the browser.

The UI for this error handling experience is part of the Blazor project templates.

在文档中,它们是 Blazor Server 详细电路错误和全局异常处理、使用持久提供程序记录错误、可能发生错误的位置、高级方案和其他资源。

此外,我在这里写了一些关于如何捕获异常的示例:

示例 1:

对于您的代码:

void IncrementCount()
{
    currentCount += 1;
    _ = 0 / (5-currentCount);  // <-- force error when currentCount is 5.
}

解决方法是:

void IncrementCount()
{
    currentCount += 1;
    try
    {
        _ = 0 / (5-currentCount);
    }
    catch (DivideByZeroException e)
    {
        // handling exception
    }
}

示例 2:

对于 .razor 页上的 DivideByZeroException

<h1> @( (0 / (5-currentCount) ).ToString()  ) </h1>

目前还不是解决方案。

已编辑 Mister Magoo 解决方法:示例 2 有一个解决方案:try..catch - 但不太实用对所有标记执行此操作

<h1>
    @try
    {
        @:@((0 / (5 - currentCount)).ToString())
    }
    catch (Exception ex)
    {
        @:@ex.Message;
    }
</h1>