Handling two WebException's properly

大憨熊 提交于 2019-11-27 15:51:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/2650758/handling-two-webexceptions-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!