【发布时间】: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 的新手,因此我们将不胜感激。
【问题讨论】: