gpt4 book ai didi

c# - 使用 webexception 捕获错误

转载 作者:太空狗 更新时间:2023-10-29 22:28:02 27 4
gpt4 key购买 nike

我正在使用一个简单的 Web 客户端从 Web 服务中检索一些 XML,我将其封装在一个简单的 try、catch block (捕获 WebException)中。像下面这样;

try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://ip/services"));
}
catch (WebException e)
{

Debug.WriteLine(e.Message);
}

不,如果我将 IP 地址更改为无效的 IP 地址,我会期望它抛出异常并将消息输出到调试窗口。但事实并非如此,似乎 catch block 甚至没有被执行。除以下内容外,没有任何内容和调试窗口;

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll

我的代码看起来很正确,所以我不明白为什么没有捕获到异常?

最佳答案

根据您对错误消息的描述,我认为抛出的实际异常是“FileNotFoundException”类型。

您是否尝试过捕获异常并检查类型?可能web异常是内部异常。

        try
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("http://ip/services"));
}
catch (Exception ex)
{

Debug.WriteLine(ex.GetType().FullName);
Debug.WriteLine(ex.GetBaseException().ToString());
}

更新:我刚刚注意到您实际调用的是一个异步方法。

作为完整性检查,我建议切换到非异步方法并检查由此产生的错误。

WebClient.DownloadString Method (Uri)

您还可以从查看此页面中获益,该页面以 Web 客户端为例介绍了捕获异步错误的过程。

Async Exceptions

关于c# - 使用 webexception 捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7991981/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com