C# 在 async/await 中正确处理 HttpClient 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19034199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:57:18  来源:igfitidea点击:

Properly handling HttpClient exceptions within async / await

c#.netasynchronouswindows-phone-8async-await

提问by Nils Holtar

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 illustrate, and it is being excecuted on both a Windows Phone 8 device and the emulator:

我希望有人能就我在使用 HttpClient 进行异步/等待异常处理方面面临的问题给我一点启发。我写了一些代码来说明,它正在 Windows Phone 8 设备和模拟器上执行:

    private async void SearchButton_Click(object sender, EventArgs e)
    {
        try
        {
            HttpClient client = new HttpClient();
            System.Diagnostics.Debug.WriteLine("BEGIN FAULTY REQUEST:");
            string response = await client.GetStringAsync("http://www.ajshdgasjhdgajdhgasjhdgasjdhgasjdhgas.tk/");
            System.Diagnostics.Debug.WriteLine("SUCCESS:");
            System.Diagnostics.Debug.WriteLine(response);
        }
        catch (Exception exception)
        {
            System.Diagnostics.Debug.WriteLine("CAUGHT EXCEPTION:");
            System.Diagnostics.Debug.WriteLine(exception);
        }
    }

Tapping the button that invokes this function, produces the following output in the debugger console, the most interesting being the ones in bold:

点击调用此函数的按钮,会在调试器控制台中产生以下输出,最有趣的是粗体

BEGIN FAULTY REQUEST:

开始错误请求:

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary

A first chance exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll

An exception of type 'System.Net.Http.HttpRequestException' occurred in mscorlib.ni.dll and wasn't handled before a managed/native boundary

System.Windows.ni.dll 中发生了“System.Net.WebException”类型的异常,并且在托管/本机边界之前未处理

System.Windows.ni.dll 中发生了“System.Net.WebException”类型的异常,并且在托管/本机边界之前未处理

mscorlib.ni.dll 中发生了“System.Net.Http.HttpRequestException”类型的第一次机会异常

mscorlib.ni.dll 中出现“System.Net.Http.HttpRequestException”类型的异常,并且在托管/本机边界之前未处理

CAUGHT EXCEPTION:

发现异常:

(and here it prints out the HttpRequestException)

(在这里它打印出 HttpRequestException)

Of course I am expecting an error in this case since the URL I am calling is nonsense. What I am not understanding here, is why the debugger reports that the exceptions are not handled, when the output simultaneously reports that the exception is caught. Also, the UI side of the app becomes much less responsive while the output is being printed, indicating that something is probably amiss.

当然,我期待在这种情况下出现错误,因为我调用的 URL 是无稽之谈。我在这里不明白的是,为什么调试器报告异常未被处理,同时输出报告异常被捕获。此外,在打印输出时,应用程序的 UI 端的响应速度会变慢,这表明可能有问题。

Is this not the way to handle exceptions when working with async and await? I appreciate any input! Thanks.

这不是在使用 async 和 await 时处理异常的方法吗?我感谢任何输入!谢谢。

采纳答案by Stephen Cleary

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.

您正在正确处理异常。

回答by Anupam

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.

附带说明一下,仅捕获特定异常,以便您了解期望的异常以及原因。

回答by mirushaki

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

当您使用 HttpClient 时,请尝试使用 response.EnsureSuccessStatusCode();

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

现在,当响应状态不是成功代码时,HttpClient 将抛出异常。

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

代码的原始来源:http: //www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client