2016-10-03 62 views
0

我張貼JSON數據API。如果我張貼錯誤的數據,catch塊沒有捕獲錯誤。控制停止在using (httpResponse = (HttpWebResponse)httpWebRequest.GetResponse())這一點,並顯示錯誤。我在做什麼錯。 以下是我的代碼,錯誤HttpWebRequest的異常處理

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

    } 
+0

你可以發佈你所得到的是錯誤的一些細節?消息,異常的類型? –

+2

如果catch沒有捕獲,則使用更通用的Exception而不是WebException。 – sachin

+0

您只捕獲webexception類型的例外。它可能會拋出一些其他類型的異常,這就是爲什麼它沒有被捕獲。我建議,你應該添加另一個泛型類型爲「Exception」的catch塊。像這樣的東西catch(Exception ex) {objTSPost.status = ex.Message; return objTSPost; } – Majid

回答

1

薩欽是正確的,你應該處理從最具體的例外,以最少的特定異常。

此外,它是不是一個好的做法傳播異常信息給用戶,因爲它可能揭示安全漏洞,而不是我建議你記錄實際的信息和傳播標準的用戶友好的消息,而不是。也許你是在方法返回值之後這樣做的,但由於其他代碼不可用,我只想給你一個提醒。

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

感謝@JFM您的寶貴寶貴意見。 –