2014-02-22 41 views
0

我的JSON字符串返回VB.Net JSON從URL到文本框我如何處理錯誤?

{ 

"name": "username", 
"place": { 
    "name": "placename", 
}  

我的代碼目前

Dim request As HttpWebRequest 
    Dim response As HttpWebResponse = Nothing 
    Dim reader As StreamReader 

    Try 

     request = DirectCast(WebRequest.Create("http://my-json.com/json"), HttpWebRequest) 

     response = DirectCast(request.GetResponse(), HttpWebResponse) 
     reader = New StreamReader(response.GetResponseStream()) 

     Dim rawresp As String 
     rawresp = reader.ReadToEnd() 

     Dim jResults As JObject = JObject.Parse(rawresp) 
     usernameTextbox.text = jResults("name").ToString() 
     placenameTextbox.text = jResults("place")("name").ToString() 

    Catch ex As Exception 
     MsgBox(ex.ToString) 
    Finally 
     If Not response Is Nothing Then response.Close() 

    End Try 

但是,當我得到一個錯誤,如404我得到一個異常

system.net.webexception: The server returned an error (404) Not Found. 

這種情況發生在該行

response = DirectCast(request.GetResponse(), HttpWebResponse) 

請你能告訴我關於我如何處理此錯誤並輸出一個消息,一個消息

感謝

+0

你正在使用'Try/Catch'塊,如果'try'塊內出現異常,它應該到'catch'塊並顯示消息框。情況並非如此嗎? – har07

+0

在我重寫它的代碼中有一些奇怪的東西,它看起來很好:S – ids

回答

0

看來我不得不改變

Catch ex As Exception 
    MsgBox(ex.ToString) 
Finally 

Catch ex As System.Net.WebException 
     MsgBox(ex.ToString) 
Finally