Retry operation on error

matm

New member
Joined
Jul 22, 2009
Messages
4
Programming Experience
Beginner
Hi there,

I'm writing a Windows service that will provision accounts in Active Directory, and I'd like to continue processing the provisioning process if an error is encountered, and then retry the operation.

For example, I might want to create an account, and then add the account to a handful of groups.

I've found that in some circumstances (such as the domain controller being temporarily under load) that a single operation in a sequence may fail, however I want the sequence to continue, record that there was an error, and then retry the entire operation.

9 out of 10 times, the retried operation will complete successfully.

My current code uses On Error Resume Next, because I couldn't find a way to continue processing using my original Try, Catch (on a side note, if anyone can recommend a way that I can use Try, Catch in this scenario, I'd appreciate that as well).

Here is the function that I have so far: -

VB.NET:
Dim errorCount As Integer = 0

Private Function CreateUser (ByVal username As String) As Boolean

On Error Resume Next

Dim didError As Boolean = False

' Create a user

If Err.Number <> 0 Then

    didError = True
    Err.Clear()

End If

' Add the user to a group

If Err.Number <> 0 Then

    didError = True
    Err.Clear()

End If

If didError = True Then

    If errorCount < 1 Then

        errorCount = errorCount + 1
        CreateUser(username)

    Else

        Return False

    End If

Else

    Return True

End If

End Function

What I'm trying to achieve here, is to check if an error has occured, and if it has, make sure that it's the first error that's occured before retrying the function by calling itself with the same ByVal that it was originally given. If it's already errored more than once, then return false.

I'd expect the above code to return true if the second attempt succeeds, but instead I'm getting a false returned, even though the operation completes successfully.

No doubt I'm either doing something fundamentally wrong, or my logic or understanding is incorrect.

Any assistance would be fantastic.
 

Latest posts

Back
Top