Properly handling HttpClient exceptions within async / await

前端 未结 3 2095
醉梦人生
醉梦人生 2020-12-24 15:12

I was hoping somebody could enlighten me a little bit on an issue I am facing in regards to async/await exception handling with HttpClient. I have written some code to illus

3条回答
  •  太阳男子
    2020-12-24 15:38

    As you are using HttpClient, try to use response.EnsureSuccessStatusCode();

    Now HttpClient will throw exception when response status is not a success code.

    try
    {
        HttpResponseMessage response = await client.GetAsync("http://www.ajshdgasjhdgajdhgasjhdgasjdhgasjdhgas.tk/");
        response.EnsureSuccessStatusCode();    // Throw if not a success code.
    
        // ...
    }
    catch (HttpRequestException e)
    {
        // Handle exception.
    }
    

    ORIGINAL SOURCE OF THE CODE: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

提交回复
热议问题