2011-09-21 114 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

相关问题