2011-09-21 63 views
1

我有一個HTTP類,從URL的內容,POST的內容到URL的內容等,然後返回原始的HTML內容。VB.NET函數作爲字符串,將返回假布爾?

在函數裏面的類檢測是否有HTTP錯誤,如果是這樣我想返回false,但是如果我已經聲明函數返回一個字符串,這將工作嗎?什麼我試圖做

代碼示例(請注意,如果檢測到一個HTTP錯誤代碼返回內容&返回FALSE)

Public Function Get_URL(ByVal URL As String) As String 
    Dim Content As String = Nothing 
    Try 
     Dim request As Net.HttpWebRequest = Net.WebRequest.Create(URL) 
     ' Request Settings 
     request.Method = "GET" 
     request.KeepAlive = True 
     request.AllowAutoRedirect = True 
     request.Timeout = MaxTimeout 
     request.CookieContainer = cookies 
     request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24" 
     request.Timeout = 60000 
     request.AllowAutoRedirect = True 
     Dim response As Net.HttpWebResponse = request.GetResponse() 
     If response.StatusCode = Net.HttpStatusCode.OK Then 
      Dim responseStream As IO.StreamReader = New IO.StreamReader(response.GetResponseStream()) 
      Content = responseStream.ReadToEnd() 
     End If 
     response.Close() 
    Catch e As Exception 
     HTTPError = e.Message 
     Return False 
    End Try 
    Return Content 
End Function 

和使用例如:

Dim Content As String = Get_URL("http://www.google.com/") 
If Content = False Then 
    MessageBox.Show("A HTTP Error Occured: " & MyBase.HTTPError) 
    Exit Sub 
End If 

回答

1

通常在這種類型的場景中,你會拋出一個新的異常並提供更詳細的信息,並讓異常冒泡到主代碼處理的狀態(或者讓原來的異常冒出來,而不是首先捕獲它)。

Catch e As Exception 
    ' wrap the exception with more info as a nested exception 
    Throw New Exception("Error occurred while reading '" + URL + "': " + e.Message, e) 
End Try 

裏面的使用例子:

Dim content As String = "" 
Try 
    content = Get_URL("http://www.google.com/") 
Catch e As Exception 
    MessageBox.Show(e.Message) 
    Exit Sub 
End Try 
+0

非常感謝您的幫助,這正是我試圖做。對VB來說還是很新的東西,但每天都會學到更多! 在函數中拋出新異常是否會拋出函數,還是會在End Try下面運行返回內容? – Chris

+1

@Chris:它會立即跳出該功能,因此內容仍然會被設置爲它的原始值「」。 – mellamokb

+0

更新:拋出一個新的異常還會顯示一個消息框,我在內部處理所有錯誤並將它們記錄到數據庫,因此不需要顯示消息框。有沒有辦法在沒有提示顯示的情況下將異常備份回來? – Chris

相關問題