处理两个WebException的正确方法

18

我正在尝试正确处理两个不同的WebException异常。

基本上它们是在调用WebClient.DownloadFile(string address, string fileName)之后被处理的。

据我所知,到目前为止,有两个我必须处理的WebException异常:

  • 无法解析远程名称(即没有网络连接以访问服务器下载文件)
  • (404)未找到文件(即服务器上不存在该文件)

可能还有其他情况,但这是我迄今发现最重要的。

那么我应该如何正确地处理它们呢?因为它们都是WebException异常,但我希望分别处理上述每种情况。

以下是我目前的处理方式:

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
        }
    }
}

您可以看到,我正在检查消息以查看WebException的类型。我认为有更好或更精确的方法来做到这一点吗?


猜测答案是检查异常状态,例如使用 Web 异常,(if wEx.Status == WebExceptionStatus.Something) { //处理 } (if wEx.Status == WebExceptionStatus.SomethingElse) { //处理那个 } - baron
1个回答

29

根据MSDN文章,您可以按照以下方式进行操作:

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
    }
}

我不确定WebExceptionStatus.NameResolutionFailure是否是你遇到的错误,但你可以检查抛出的异常并确定该错误的WebExceptionStatus是什么。


我还在这里看了一下:http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus.aspx,它展示了所有可能的状态。你说的那两个状态是正确的,在每种情况下我都得到了它们。我已经决定单独处理404,然后对于任何其他异常状态使用else - 因为其他所有状态似乎都与连接和网络连接有关,我将把它们分组。 - baron

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接