httpwebrequest异常处理错误

本文关键字:错误 异常处理 httpwebrequest | 更新日期: 2023-09-27 18:11:18

我正在向API发布JSON数据。如果我发布错误的数据,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;
        }
    }

httpwebrequest异常处理错误

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