如何从头开始重试Try and Catch

时间:2018-05-18 21:12:12

标签: vb.net error-handling

我有一个公共功能,我打电话给我的RestApi发送请求。我的RestAPI 如果我有一个有效的令牌,需要一个有效的jwt来访问受限制的资源,并且一切正常。如果我的令牌过期,我的RestAPI会返回一个401令牌过期,我在WebException中捕获。到目前为止一切顺利,我创建了一个新功能来获得一个新的令牌,但我想要做的是在获得一个新令牌后再次发出相同的请求。那么我怎么能让代码尝试再次执行,只有一次,所以如果在服务器上出现问题,我们不会在一个死循环中一遍又一遍地获取新的令牌。

radians0 + .pi

3 个答案:

答案 0 :(得分:0)

一种可能的解决方案是在getSimpleData中添加一个参数,指示您是否应该在失败时重试。

Public Function getSimpleData(ByVal myBaseURL As String, ByVal myQuery As String, _
ByVal Auth As Boolean, ByVal retry As Boolean) As String

然后在try catch中利用该参数确保您只重试一次:

If ExResponse.StatusCode = "401" And resp.Contains("Token expired") Then

    If retry = True Then

        getNewToken()

        'Pass false for retry value this time so it won't keep retrying.
        getSimpleData(myBaseURL, myQuery, Auth, False)

    End If

End If

答案 1 :(得分:0)

您可以在循环中添加Try-Catch块,其中的变量表示失败次数。这有助于您轻松控制尝试次数:

Dim errorCounter As Integer = 0

Do
    Try
        ' Create the web request 
        ' ..
    Catch ex As WebException
        ' ..
        If ExResponse.StatusCode = "401" AndAlso resp.Contains("Token expired") Then
            errorCounter += 1
            getNewToken()
        Else
            ' ..
        End If
    End Try
Loop While errorCounter > 0 AndAlso errorCounter < 2      ' Change this to increase
                                                          ' the number of tries.

附注:此处并没有太大的区别,但您应该使用AndAlso代替And。请参阅:Which is better for performance? And vs AndAlso

答案 2 :(得分:0)

好的,我能够理解这一点,我使用了N0Alias Retry Approach,因为我只想尝试一次以避免无休止的循环。我也用Ahmed和AndAlso替换AND子句。最大的问题是,即便如此,我仍然能够重新运行我丢失了返回值的功能,即使代码命中它也是如此。下面的代码修复了所有。

  Public Function getSimpleData(ByVal myBaseURL As String, ByVal myQuery As String, ByVal Auth As Boolean, ByVal Retry As Boolean) As String
    Dim Request As HttpWebRequest
    Dim Response As HttpWebResponse = Nothing
    Dim myResponse As String

    Try
        ' Create the web request  
        Request = DirectCast(WebRequest.Create(myBaseURL & myQuery), HttpWebRequest)
        ' If Auth is Set we will send Bearer Token
        If Auth = True Then
            Request.Headers("Authorization") = "Bearer " & Trim(frmMain.jwt)
        End If

        ' Get response  
        Response = DirectCast(Request.GetResponse(), HttpWebResponse)


        Dim resp = New StreamReader(response.GetResponseStream()).ReadToEnd()
        myResponse = resp
        Return myResponse


    Catch ex As WebException
        Dim ExResponse = TryCast(ex.Response, HttpWebResponse)
        Dim ExResp = New StreamReader(ex.Response.GetResponseStream()).ReadToEnd()

        If ExResponse.StatusCode = "401" AndAlso ExResp.Contains("Token expired") Then
            Console.WriteLine("Need new Token")
            If Retry = True Then
                getNewToken()
                myResponse = getSimpleData(myBaseURL, myQuery, Auth, False)
                Return myResponse

            End If
        Else

            Return ExResp

        End If
        If Not ExResponse Is Nothing Then ExResponse.Close()
    Catch ex As Exception

    Finally
        If Not Response Is Nothing Then Response.Close()

    End Try


End Function