簡體   English   中英

如果在 inte.net 斷開連接時外部 api 失敗,我想捕獲異常

[英]I want to catch the exception if external api failed when internet disconnected

private async Task<IEnumerable<Result>> searchresult(string searchText)
{
    try
    {
        rootdata = await HttpClientJsonExtensions.GetFromJsonAsync<Rootdata>(httpClient,$"https://expressentry...");
    }
    catch (WebException ex)
    {
    }

    addresslist = rootdata.d.Results.ToList();

    return addresslist;
}

在這種情況下,瀏覽器中發生未處理的錯誤並檢查檢查顯示

加載資源失敗:ERR_INTE.NET_DISCONNECT

但我想處理那個例外。

請幫我。

謝謝

因為您正在嘗試使用WebException捕獲錯誤並且ERR_INTE.NET_DISCONNECT is HttpRequestExceptionWebException更改為Exception以獲取所有異常

是這樣的:

private async Task<IEnumerable<Result>> searchresult(string searchText)
{
    var addresslist = new Rootdata();
    try
    {
        rootdata = await HttpClientJsonExtensions.GetFromJsonAsync<Rootdata>(httpClient,$"https://expressentry...");

        addresslist = rootdata.d.Results.ToList();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return addresslist;
}

除了使用錯誤的異常之外,我感到您在嘗試從 API 故障中獲取適當的錯誤消息時很痛苦。

我改為使用PostAsyncGetAsync ,這樣我就可以從請求中獲取實際的HttpResponseMessage 現在我可以檢查StatusCodes以及訪問服務器返回的內容。

如果服務器返回內容,我發現通常是最好的 API 特定錯誤消息。 http StatusCodes將是通用的,而不特定於 API。異常本身可以是任何東西。 因此,當我收到錯誤時,我會優先考慮;

  • 響應內容
    • 示例: “API 密鑰無效。最大長度為 255。”
  • 響應狀態碼
    • 示例: “401:未經授權。”
  • 異常信息
    • 示例: “對象引用未設置為 object 的實例。”

這可能看起來像這樣:

string error = string.Empty;
HttpResponseMessage response = null;
try
{
    response = await _httpClient.GetAsync("some request");
    if (response.IsSuccessStatusCode)
    {
        // Do work
    }
    else
        error = await HandleError(response);
}
catch (Exception ex)
{
    error = await HandleError(response, ex);
}


private async Task<string> HandleError(HttpResponseMessage response, Exception ex = null)
{
    string error = string.Empty;
    // If the API returned a body, get the message from the body.
    // If you know the content type you could cast to xml/json and grab the error property opposed to all of the content.
    if (response != null && response.Content != null)
        error = $"{response.StatusCode} {response.ReasonPhrase} {await response.Content.ReadAsStringAsync()}";
    else if (response != null && string.IsNullOrEmpty(error))
        error = $"{response.StatusCode} {response.ReasonPhrase}"; // Fallback to response status (401 : Unauthorized).
    else if (ex != null && string.IsNullOrEmpty(error))
        error = ex.Message; // Fall back to exception message.
    else
        return "Unhandled";

    return error;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM