我有一个HTTP类,它从URL获取内容,POST的内容到URL等,然后返回原始HTML内容。
在类的内部函数中,它检测是否存在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
答案 0 :(得分: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