受欢迎的博客标签

Global Error Handling in ASP.NET Core Blazor Server 5.x

Published

.Net 5.x

https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-5.0

Error Handling  in Page Razor

1.errors may occur where  call service

protected override async Task OnParametersSetAsync()
    {


        try
        {
            loadFailed = false;
            forecasts = await StockDataService.GetStockInfo(currentCount);

            Logger.LogInformation("Failed to load product ");
        }
        catch (Exception ex)
        {
            loadFailed = true;
            // Logger.LogWarning(ex, "Failed to load product {ProductId}", ProductId);
        }
    }

 

2.errors may occur where  call web api


<!--come from:https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/handle-errors?view=aspnetcore-5.0-->
@if (forecasts != null)
{
    <h1>has data.</h1>
}
else if (loadFailed)
{
    <h1>Sorry, we could not load this data due to an error when call web api.</h1>
}
else
{
    <h1>Loading...</h1>
}
 
@code {
private async void HandleValidSubmit()
    {
        forecasts = null;
        isLoading = true;

        Logger.LogInformation($"Call Web Api {GlobalHelper.BaseUrl} + /api/v1/StockDataPhysicalDiskMultiFilterPankou/MenuAsync");

        HttpResponseMessage response = await Http.PostAsJsonAsync<MultiFilterSearchModel>(GlobalHelper.BaseUrl + "/api/v1/StockDataPhysicalDiskMultiFilterPankou/SearchAsync", searchModel);



        @if (response.IsSuccessStatusCode)
        {
            string jsonResponse = await response.Content.ReadAsStringAsync();

            Logger.LogInformation($"json string from Response body: {jsonResponse}");

            forecasts = System.Text.Json.JsonSerializer.Deserialize<Stockso.Models.ApiResponse<SearchResultStockModel>>(jsonResponse);

            if (forecasts != null)
            {
                //   forecasts = result.Items;
            }
            else
            {
                //  navigationManager.NavigateTo("/registration");
            }

            //Update UI

            this.StateHasChanged();
        }
        else  //error 
        {
            Logger.LogError($"response.StatusCode: {response.StatusCode.ToString()}");
        }


        isLoading = false;


        Console.WriteLine("OnValidSubmit");
    }
}