Properly handling HttpClient exceptions within async / await

前端 未结 3 2054
醉梦人生
醉梦人生 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:17

    This is an artifact of the debugger. It's determining that an exception is "uncaught" because it's not caught yet. In this case this is expected behavior.

    You are handling the exceptions correctly.

    0 讨论(0)
  • 2020-12-24 15:30

    The debugger is telling you that this exception is first chance. When a debugger is attached to your process it gets notified for every exception that is thrown and then based on how the debugger has been configured it will decide what to do with it. You can go through What is first chance exception? for more details.

    On a side note, catch specific exceptions only so that you understand which exceptions you are expecting and why.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题