【问题标题】:Better implementation of Blazor WASM Api response?更好地实现 Blazor WASM Api 响应?
【发布时间】:2021-07-02 23:57:11
【问题描述】:

我有一个 http 服务在我的 Blazor WASM 项目中注入 HttpClient 类。我有这样的方法:

public async Task<CommunityDto> GetCommunity(Guid CommunityId)
{
   if (string.IsNullOrEmpty(CommunityId.ToString())) return null;
   var response = await _httpClient.GetAsync($"api/communities/{CommunityId}");
   if (response.IsSuccessStatusCode)
   {
      var content = await response.Content.ReadAsStringAsync();
      return JsonSerializer.Deserialize<CommunityDto>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
   }
   else
   {
      throw new Exception(response.ReasonPhrase);
   }
}

在我的组件中,我有以下内容:

protected async override Task OnInitializedAsync()
{
   try
   {
      CommunityFromAPI = await CommunityService.GetCommunity(Id);
   }
   catch (Exception ex)
   {
      ToastService.ShowError($"Failed to get community! {ex.Message}");
      NavManager.NavigateTo("/");
    }
}

除了全局异常处理,有没有更好的处理方法?我故意从我的 API 返回 400 错误,而我的“catch”没有捕捉到异常并抛出 toast 消息。我是 Blazor 的新手,因此我们将不胜感激。

【问题讨论】:

    标签: blazor blazor-webassembly


    【解决方案1】:

    总体而言,您的设计绝对走在正确的轨道上,感谢您为 Blazor 应用程序中的错误提供用户反馈。

    我有几个建议。

    1. 使用 API 客户端的 exception.Message 向您的用户呈现是可以的,但它会将您的 UI 与 API 访问层中的错误耦合起来。例如,假设您的 API 不可用并且 GetAsync 抛出 HttpRequestException,那么您将向用户显示错误消息文本。一种选择是引入您自己的异常类型,由您的 API 层抛出,由您的 UI 捕获并有意显示给用户。另一种选择是让您的 API 层返回 null,然后在您的 UI 中向用户显示一般错误消息(如“社区不可用”)。另一个选项(已经建议)是从您的 API 层引入一个“返回类型”,其中包含数据和/或错误状态(但该实现应该是通用的,即ApiResponse&lt;TReturnData&gt;)。所有选项,包括您的选项,都可以正常工作。在考虑选项时,我会问自己“我真正想向用户显示哪些错误消息?哪些代码最容易维护?”

    2. 第二个建议是,如果您可以使用扩展方法ReadFromJsonAsync&lt;&gt; (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.json.httpcontentjsonextensions.readfromjsonasync?view=net-5.0),那么您可以将此代码缩短为:

       if (response.IsSuccessStatusCode)
       {
            return await response.Content.ReadFromJsonAsync<CommunityDto>(
                            new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
       }  
      

    【讨论】:

    • 我可以在我的客户端 Blazor 项目中修改自定义对象以检查状态代码并显示友好的 UI 消息。在 Angular 中,如果需要,我们可以在我们的 http 客户端调用上进行联合,以返回自定义错误对象。我希望 Blazor 可以处理联合数据
    【解决方案2】:

    我通常会这样创建一个复合对象:

    public class ResultObj
        {
            public ResultObj(YourClass result, string errorCode = null, string errorMessage = null)
            {
                this.Result= resultados;
                this.ErrorCode = codigoErro;
                this.ErrorMessage = mensagemErro;
            }
    
            public string ErrorMessage { get; set; }
            public List<object> Result{ get; set; }
            public string ErrorCode { get; set; }
        }
    

    在您的调用中,您将其转换为 try catch 块,以防序列化失败。

    如果序列化工作正常,那么您检查 ErrorCode 和 ErrorMessage 字段,然后调用您的 toast 等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-13
      • 1970-01-01
      • 2021-03-23
      • 2022-10-26
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多