Hi VBFroums, will keep this post short, don't need to write an essay lol.
When I call the SendRequestAsync method, and an error occurs in ResponseCallback or ReadCallback, how can it be caught in the calling code using a Try...Catch block?
Example:
Try
Dim req as Net.HttpWebRequest = Net.HttpWebRequest.Create("http://thisdomainwillthrowanexception182.com")
WebRequester.SendRequestAsync(req)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Instead of showing me a message box with the unable to connect to remote server error (since the example domain is invalid), the error is not being caught by the Try...Catch block. Can I not do it??
Code:
Imports System.Net
Public Class RequestState
Public request As Net.HttpWebRequest
Public response As Net.HttpWebResponse
Public responseStream As IO.Stream
Public buffer(1024) As Byte
Public requestData As New Text.StringBuilder
Public responseData As String
Sub New()
request = Nothing
responseStream = Nothing
End Sub
End Class
Public Class WebRequester
Public Shared Sub SendRequestAsync(request As HttpWebRequest)
Dim myRequestState As New RequestState
myRequestState.request = request
Dim iarResponse As IAsyncResult = CType(myRequestState.request.BeginGetResponse(New AsyncCallback(AddressOf ResponseCallback), myRequestState), IAsyncResult)
End Sub
Private Shared Sub ResponseCallback(ar As IAsyncResult)
Dim rs As RequestState = CType(ar.AsyncState, RequestState)
Dim req As Net.HttpWebRequest = rs.request
Dim resp As Net.HttpWebResponse = CType(req.EndGetResponse(ar), Net.HttpWebResponse)
rs.response = resp
Dim ResponseStream As IO.Stream = resp.GetResponseStream()
rs.responseStream = ResponseStream
Dim iarRead As IAsyncResult = ResponseStream.BeginRead(rs.buffer, 0, 1024, New AsyncCallback(AddressOf ReadCallback), rs)
End Sub
Private Shared Sub ReadCallback(asyncResult As IAsyncResult)
Dim rs As RequestState = CType(asyncResult.AsyncState, RequestState)
Dim responseStream = rs.responseStream
Dim read As Integer = responseStream.EndRead(asyncResult)
If read > 0 Then
Dim charBuffer(1024) As Char
Dim streamDecoder As Text.Decoder = Text.Encoding.UTF8.GetDecoder()
Dim len As Integer = streamDecoder.GetChars(rs.buffer, 0, read, charBuffer, 0)
Dim str As New String(charBuffer, 0, len)
rs.requestData.Append(Text.Encoding.ASCII.GetString(rs.buffer, 0, read))
Dim iarRead As IAsyncResult = responseStream.BeginRead(rs.buffer, 0, 1024, New AsyncCallback(AddressOf ReadCallback), rs)
Else
responseStream.Close()
End If
End Sub
End Class
Example:
Try
Dim req as Net.HttpWebRequest = Net.HttpWebRequest.Create("http://thisdomainwillthrowanexception182.com")
WebRequester.SendRequestAsync(req)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Instead of showing me a message box with the unable to connect to remote server error (since the example domain is invalid), the error is not being caught by the Try...Catch block. Can I not do it??