我调用的方法可能会在覆盖的函数中抛出异常。如果MyBase.GetWebResponse()
抛出异常,我怎么能从主代码中捕获它?调试器在GetWebResponse
停止,而不是在主Try
。
我使用覆盖函数来获取重定向的ResponseUri。不使用GetWebResponse
,我可以捕获异常。
主要代码:
Try
RetryAction(Sub()
Using cawc As New CookieAwareWebClient)
strContent = cawc.DownloadString(m_url)
m_url = cawc.ResponseUri.ToString
End Using
End Sub, 10, 1000)
Catch ex As WebException
StreamNotAvailable(ex)
End Try
功能:
Public Sub RetryAction(action As Action, numRetries As Integer, retryTimeout As Integer)
If action Is Nothing Then
Throw New ArgumentNullException("action")
End If
' slightly safer...
Do
Try
action()
Exit Sub
Catch
If numRetries <= 0 Then
Throw
Else
' improved to avoid silent failure
Thread.Sleep(retryTimeout)
End If
End Try
Loop While Interlocked.Decrement(numRetries) > -1
End Sub
类别:
Public Class CookieAwareWebClient
Inherits WebClient
...
Private m_ResponseUri As Uri
Public ReadOnly Property ResponseUri() As Uri
Get
Return m_ResponseUri
End Get
End Property
Protected Overrides Function GetWebResponse(request As WebRequest) As WebResponse
Dim response As HttpWebResponse = MyBase.GetWebResponse(request)
m_ResponseUri = response.ResponseUri
Return response
End Function
End Class
答案 0 :(得分:0)
我终于找到了解决方案:
Try
RetryAction(Sub()
Try
Using cawc As New CookieAwareWebClient)
strContent = cawc.DownloadString(m_url)
m_url = cawc.ResponseUri.ToString
End Using
Catch ex As Exception
Throw
End Try
End Sub, 10, 1000)
Catch ex As WebException
StreamNotAvailable(ex)
End Try