2012-07-08 42 views
0

我是新來的VB ...我使用下面的代碼,以使一個HTTP請求和緩衝響應爲一個字符串錯誤方式:更好地處理與HTTP請求/響應

Try 
      myHttpWebRequest = CType(WebRequest.Create(strUrl), HttpWebRequest) 
      myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse) 
      receiveStream = myHttpWebResponse.GetResponseStream() 
      encode = System.Text.Encoding.GetEncoding("utf-8") 
      sr = New StreamReader(receiveStream, encode) 

      Do Until sr.Peek = -1 
       strLine = String.Concat(strLine, sr.ReadLine) 
       arrBuff.Add(strLine) 
      Loop 
     Catch ex As System.Net.WebException 
      MsgBox(ex.Message) 
     Finally 
      myHttpWebResponse.Close() 
     End Try 
     sr.Close() 

這工作正常,但錯誤處理不好,例如,如果請求觸發500響應,VB代碼遇到未處理的異常。關於如何使這段代碼更好的想法?

回答

1

使用HttpWebResponse.StatusCode來確定服務器是否向您發送了任何內容(可能是)200(確定)。

1

而不是使用一個MsgBox,如下所示引發異常:

Catch ex As Exception 
    Throw New Exception(ex.Message) 

如果您正在從網頁中的AJAX調用,您可以檢索該郵件利用:

Catch ex As Exception 
    HttpContext.Current.Response.Write(ex.Message); 
    HttpContext.Current.Response.StatusCode = 500;