Search code examples
vb.nethttpwebrequest

How can I prevent my VB application to crash


I hope that you can help me with my problem.

I get this error:

System.Net.WebException:
The remote server returned an error: (401) Unauthorized.

when I click on button_2. I want to prevent the application from crashing using, show a MessageBox error or something similar.
Can anyone help?

Private Sub Guna2Button1_Click(sender As Object, e As EventArgs) Handles Guna2Button1.Click
    Dim api As String
    api = Guna2TextBox1.Text
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("link")
    Dim wc As New WebClient
    Dim data As String
    Dim response As System.Net.HttpWebResponse
    Try
        response = request.GetResponse()
    Catch ex As System.Net.WebException
        MsgBox("Bad API")
    End Try
    MsgBox("Good API")

        data = wc.DownloadString("link")
        Dim IPV4Regex = New Regex("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
        Dim ipstr As String = ("")
        Dim total As String = ("")
        Dim myJObject = JObject.Parse(data)

        For Each match In myJObject("matches")
            Dim ip = match("http")("host")
            If IPV4Regex.Match(ip).Success Then
                ipstr = ip
                total = total + ipstr & vbCrLf
                Guna2TextBox2.Text = total
                Label4.Visible = True
            End If
        Next
End Sub

Solution

  • Try this

    Dim response As System.Net.HttpWebResponse
    
                Try
                    response = request.GetResponse()
                'Put other lines here...
                Catch ex As System.Net.WebException
                    msgbox("Something bad happened")
                End Try