0

私はVBを初めて使用しています...次のコードを使用して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 コードは未処理の例外に遭遇します。このコードを改善する方法について何か考えはありますか?

4

2 に答える 2

1

MsgBoxを使用する代わりに、次のように例外を発生させます。

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

WebページからAJAX呼び出しを行う場合は、次を使用してメッセージを取得できます。

Catch ex As Exception
    HttpContext.Current.Response.Write(ex.Message);
    HttpContext.Current.Response.StatusCode = 500;
于 2012-07-08T19:07:53.437 に答える
1

を使用しHttpWebResponse.StatusCodeて、サーバーが (おそらく) 200 (OK) 以外のメッセージを送信したかどうかを判断します。

于 2012-07-08T18:33:57.293 に答える