Blazor 全局异常处理

时间:2021-04-05 07:15:38

标签: blazor blazor-server-side

我正在尝试按照此链接中解释的有关 Blazor 中的全局异常处理的 MS 文章进行操作

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-5.0&pivots=server#global-exception-handling-1

按照其中的步骤操作后,我原本希望在索引页内容中看到错误异常,但结果却出现在 2 个单独的部分 enter image description here image

任何想法如何将错误显示在索引页面的内容内?

代码

ErrorCasCading 组件

@using Microsoft.Extensions.Logging
@inject ILogger<Error> Logger

<CascadingValue Value=this>
    @ChildContent
</CascadingValue>

<LayoutView Layout="@typeof(MainLayout)">
    <h1>Sorry, An error happen</h1>
    <p>An error happen, please try again.</p>
</LayoutView>

@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; }
    private string MyProperty;
    public void ProcessError(Exception ex)
    {
        MyProperty = "An error happen, please try again";
        Logger.LogError("Error:ProcessError - Type: {Type} Message: {Message}",
            ex.GetType(), ex.Message);
        StateHasChanged();
    }
}

App.Razor

<CascadingAuthenticationState>
    <ErrorCasCading>
        <Router AppAssembly="@typeof(App).Assembly"
                AdditionalAssemblies="new[] {
                              typeof(Login).Assembly
                              }">
            <Found Context="routeData">
                <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
                    <NotAuthorized>
                        <h1>Sorry, you're not authorized to view this page.</h1>
                        <p>You may want to try logging in (as someone with the necessary authorization).</p>
                    </NotAuthorized>
                </AuthorizeRouteView>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(MainLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
    </ErrorCasCading>
</CascadingAuthenticationState>```

0 个答案:

没有答案