如何从Web客户端和httpwebrequest中查找是否发生了异常?

时间:2013-12-31 10:56:43

标签: c# exception httpwebrequest webclient

假设我有一种方法可以执行以下操作,它只是一种测试方法,只是为了显示我真正需要的东西。

 public void ExceptionOccured()
        {
            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
                Stream _data = client.OpenRead(_apiCallArgs);
                // if exception occurs in Open read method

                WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                // if exception occurs in get response method

                int a = Convert.ToInt32("anyvariable");
                // if exception occurs here
            }
            catch (Exception ex)
            {
                // how can i find that who occurred the exception either its is occurred by webclient or httprequest or by coversion ?
            }


        }

我怎样才能找出发生异常的人是由webclient还是httprequest发生的,还是通过coversion发生?

1 个答案:

答案 0 :(得分:1)

    public void ExceptionOccured()
    {
        try
        {
            WebClient client = new WebClient();
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            Stream _data = client.OpenRead(_apiCallArgs);
            // if exception occurs in Open read method

            WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // if exception occurs in get response method

            int a = Convert.ToInt32("anyvariable");
            // if exception occurs here
        }
        catch (Exception ex)
        {
           Type exType = ex.GetBaseException().GetType();
        }


    }

OR

    public void ExceptionOccured()
    {
        try
        {
            WebClient client = new WebClient();
            client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            Stream _data = client.OpenRead(_apiCallArgs);
            // if exception occurs in Open read method

            WebRequest request = WebRequest.Create("http://www.contoso.com/default.html");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // if exception occurs in get response method

            int a = Convert.ToInt32("anyvariable");
            // if exception occurs here
        }
        catch (WebException exhttp)
        {
             //Web exception directally catch by this block
        }
        catch (Exception ex)
        {

        }


    }