httpwebrequest异常处理中的错误

时间:2016-10-03 06:54:14

标签: c# httpwebrequest httpwebresponse

我将JSON数据发布到API。如果我发布了错误的数据,catch阻止不会发现错误。控制在此点using (httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())处停止并显示错误。我做错了什么。 以下是我的代码,

try
        {

            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            var httpWebRequest = (HttpWebRequest)WebRequest.Create("ipaddress");
            httpWebRequest.Credentials = new NetworkCredential("", "");
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";

            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string name = objTSPost.name;
                string servicetype = objTSPost.service_type;
                string json = "{\"name\":\"VMR_" + name + "\"," +
                              "\"service_type\":\"" + servicetype + "\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }


            using (httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }
                string str = "{\"name\":\"VMR_" + objTSPost.name + "\"," +
                                  "\"service_type\":\"" + objTSPost.service_type + "\"}";
                var data = JsonConvert.DeserializeObject<TSGetRootObject>(str);
                data.status = ((HttpWebResponse)httpResponse).StatusDescription;
                return data;
            }

        }
        catch (WebException ex)
        {
            objTSPost.status = ex.Message;
            return objTSPost;
        }

    }

1 个答案:

答案 0 :(得分:1)

Sachin是正确的,您应该处理从最具体到最不具体的异常的异常。

将异常消息传播给用户也不是一个好的做法,因为它可能会泄露安全漏洞,而是建议您记录实际消息并传播标准的用户友好消息。也许你在方法返回它的值之后就这样做了,但由于其余代码不可用,我只想提醒你。

    try
    {

        //My maybe not toally reliable code

    }
    catch (WebException ex)
    {
        LogMessage(ex.Message);
        objTSPost.status = "My custom userfriendly specific web exception message";
        return objTSPost;
    }
    catch(Exception ex)
    {
        LogMessage(ex.Message);
        objTSPost.status = "My custom userfriendly unhandled exception message";
        return objTSPost;
    }