dpskipper dpskipper - 3 months ago 37
Vb.net Question

Error Handling with HTTPWebRequests, VB.NET

I've looked around and couldn't find an answer so I thought i'd ask it here.
I have a program the calls an API with login info passed in the header and the server returns some info upon authentication. The problem is if the user creds are incorrect, the program crashes and throws an exception. The error is 401. How do it catch this, and tell the user?
My code is:

Dim request = TryCast(System.Net.WebRequest.Create("https://myurl.com"), System.Net.HttpWebRequest)

request.Method = "GET"

request.Headers.Add("authorization", "Bearer " + AccessToken)

request.ContentLength = 0
Dim responseContent As String
Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
Using reader = New System.IO.StreamReader(response.GetResponseStream())
responseContent = reader.ReadToEnd()
MessageBox.Show(responseContent)
End Using
End Using


Thanks.

Answer

Use a try catch statement

try
   'My error prone code
catch ex as Exception
   'Handle my error
end try

    Try

        Dim request = TryCast(System.Net.WebRequest.Create("https://myurl.com"), System.Net.HttpWebRequest)

        request.Method = "GET"

        request.Headers.Add("authorization", "Bearer " + AccessToken)

        request.ContentLength = 0
        Dim responseContent As String
        Using response = TryCast(request.GetResponse(), System.Net.HttpWebResponse)
            Using reader = New System.IO.StreamReader(response.GetResponseStream())
                responseContent = reader.ReadToEnd()
                MessageBox.Show(responseContent)
            End Using
        End Using

    Catch ex As Exception
        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
Comments