下面的函数采用任何 wcf 服务方法并调用它。
Private Function ServiceCall(ByVal functionToCall As ServiceDelegate(Of IEmpService)) As Object
Dim channel As New ChannelFactory(Of IEmpService)(_endPoint)
Dim serv As IEmpService
Dim result As Object = Nothing
Dim mostRecentExp As Exception = Nothing
Dim noOfRetries As Integer = My.Settings.NoOfRetries
Dim initialDelay As Integer = My.Settings.InitialDelayInMS
serv = channel.CreateChannel()
For i As Integer = 0 To noOfRetries
Try
result = functionToCall.Invoke(serv)
mostRecentExp = Nothing
Exit For
Catch cte As ChannelTerminatedException
mostRecentExp = cte
Thread.Sleep(initialDelay * (i))
Catch enf As EndpointNotFoundException
mostRecentExp = enf
Thread.Sleep(initialDelay * (i))
Catch stb As ServerTooBusyException
mostRecentExp = stb
Thread.Sleep(initialDelay * (i))
Catch vf As FaultException(Of ValidationFault)
'no retry
Catch exp As Exception 'any other exception
mostRecentExp = exp
Thread.Sleep(initialDelay * (i))
Finally
If channel.State = CommunicationState.Faulted Then
channel.Abort()
Else
channel.Close()
End If
End Try
Next
If mostRecentExp IsNot Nothing Then
Throw New ServiceExceptions(String.Format("Call to method {0} failed", functionToCall.ToString()), mostRecentExp.InnerException)
End If
Return result
End Function
我根据我得到的异常类型确定是否需要重试,这一切都很好。我面临的问题是result = functionToCall.Invoke(serv)
结果是一个对象并且它可以包含一个自定义错误对象,在这种情况下它不会是一个例外。要解决错误,我可以做类似的事情:
If TypeOf result Is SaveAddressResponse Then
ElseIf TypeOf result Is SaveDetailResponse Then
End If
看起来很乱所以想知道我是否可以使用委托从return
对象中获取错误?