VB.Net JSON From URL To Textbox How Can I Handle Errors?

限于喜欢 提交于 2019-12-25 04:28:43

问题


My JSON String Returned

{

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

My Code At The Moment

    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

But when i get an error like 404 i get an exception

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

this happens at the line

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

please could you advise me on how i can handle this error and output a message to a messagebox

Thanks


回答1:


seems i had to change

    Catch ex As Exception
    MsgBox(ex.ToString)
Finally

To

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


来源:https://stackoverflow.com/questions/21948825/vb-net-json-from-url-to-textbox-how-can-i-handle-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!