2011-09-21 5 views
1

私は、URLのコンテンツを取得し、POSTのコンテンツをURLのものにして、生のHTMLコンテンツを返します。VB.NET関数の文字列として、Falseを返しますか?

クラス内の関数では、HTTPエラーがあるかどうかを検出し、そうであればfalseを返すが、文字列を返す関数が宣言されている場合は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の下のReturn Contentを実行するのでしょうか? – Chris

+1

@Chris:それはすぐに機能から逸脱するので、コンテンツはそれでも ""の元の値に設定されます。 – mellamokb

+0

更新:新しい例外をスローするとメッセージボックスも表示されます。私はすべてのエラーを内部的に処理し、データベースに記録してメッセージボックスの表示を必要としません。プロンプトが表示されずに回線を戻して例外をスローする方法はありますか? – Chris