处理两个引发WebException的正确 [英] Handling two WebException's properly
问题描述
我试图妥善处理两个不同的引发WebException
的。
基本上他们都呼吁 WebClient.DownloadFile(字符串的地址,字符串文件名)
$ b
据我所知,到目前为止,有两个我都要处理,双方的引发WebException
:
- 远程名称不能被解析(即没有网络连接来访问服务器上下载文件)
- (404)文件不nound(即文件不存在于服务器上)
有可能更多,但是这是我发现最重要的为止。
所以,我应该如何处理这个正确的,因为它们都引发WebException
的,但我想处理上述各种情况。不同的
这是我迄今为止:
尝试
{使用
(VAR的客户=新的WebClient())
{
client.DownloadFile(...);
}
}
赶上(InvalidOperationException异常ioEx)
{
如果(ioEx是引发WebException)
{
如果(ioEx.Message.Contains (404)
{
//处理404
}
如果(ioEx.Message.Contains(远程名称无法)
{
//处理文件不存在
}
}
}
正如你可以看到我检查的消息,看看它是什么类型引发WebException的。我会假设有一个更好的,或这样做吗?
<一个更精确的方法p>感谢
根据的this MSDN文章,你可以做大意如下的内容:
试
{
//尝试在这里下载文件
}
赶上(引发WebException前)
{
如果(ex.Status == WebExceptionStatus.ProtocolError)
{
如果(((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
//处理这里的404
}
}
,否则如果(ex.Status == WebExceptionStatus.NameResolutionFailure)
{
//处理名称解析失败
}
}
我不能肯定 WebExceptionStatus.NameResolutionFailure
是错误您所看到的,但你可以检查所抛出的异常,并确定 WebExceptionStatus
该错误的。
什么
I am trying to handle two different WebException
's properly.
Basically they are handled after calling WebClient.DownloadFile(string address, string fileName)
AFAIK, so far there are two I have to handle, both WebException
's:
- The remote name could not be resolved (i.e. No network connectivity to access server to download file)
- (404) File not nound (i.e. the file doesn't exist on the server)
There may be more but this is what I've found most important so far.
So how should I handle this properly, as they are both WebException
's but I want to handle each case above differently.
This is what I have so far:
try
{
using (var client = new WebClient())
{
client.DownloadFile("...");
}
}
catch(InvalidOperationException ioEx)
{
if (ioEx is WebException)
{
if (ioEx.Message.Contains("404")
{
//handle 404
}
if (ioEx.Message.Contains("remote name could not")
{
//handle file doesn't exist
}
}
}
As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this?
Thanks
Based on this MSDN article, you could do something along the following lines:
try
{
// try to download file here
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
{
// handle the 404 here
}
}
else if (ex.Status == WebExceptionStatus.NameResolutionFailure)
{
// handle name resolution failure
}
}
I'm not certain that WebExceptionStatus.NameResolutionFailure
is the error you are seeing, but you can examine the exception that is thrown and determine what the WebExceptionStatus
for that error is.
这篇关于处理两个引发WebException的正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!