请为我提供以下问题的任何合适的解决方案,
当 blazor 应用程序抛出任何异常时,整个应用程序就会崩溃并且没有链接起作用,直到我可以再次通过工作室运行该应用程序。
对于这个问题该怎么办?
谢谢并致以诚挚的问候
Edited
(为了提供所需的信息)
重现步骤:
创建 blazor 服务器端应用程序:
修改增量计数
At Counter.razor
:
void IncrementCount()
{
currentCount += 1;
_ = 0 / (5-currentCount); // <-- force error when currentCount is 5.
}
Push Click Me
按钮 5 次以引发错误。
尝试导航到其他应用程序页面(主页、获取数据)没有任何反应,因为它在客户端上默默失败。
附加信息
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 月编辑
幸运的是,我们现在有这方面的官方文献::
当 Blazor 应用在开发过程中无法正常运行时,从应用接收详细的错误信息有助于排除故障并解决问题。发生错误时,Blazor 应用程序会在屏幕底部显示浅黄色条:
- 在开发过程中,该栏会将您引导至浏览器控制台,您可以在其中看到异常。
- 在生产中,该栏会通知用户发生了错误并建议刷新浏览器。
此错误处理体验的 UI 是 Blazor 项目模板的一部分。
在文档中,它们是 Blazor 服务器详细电路错误、全局异常处理、持久提供程序的日志错误、可能发生错误的位置、高级方案和其他资源。
另外,我在这里写了一些关于如何捕获异常的示例:
样本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:
For DivideByZeroException
on .razor
page:
<h1> @( (0 / (5-currentCount) ).ToString() ) </h1>
目前它们还不是解决方案。
Edited解决办法马古先生 https://stackoverflow.com/users/2658697/mister-magoo: 示例2有一个解决方案:try..catch
- 但对所有标记执行此操作不太实际
<h1>
@try
{
@:@((0 / (5 - currentCount)).ToString())
}
catch (Exception ex)
{
@:@ex.Message;
}
</h1>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)