How to Retry a Statement on Error

How to retry a statement on error?

I usually put the try block in a loop,
and exit the loop when it no longer fails or the maximum number of attempts is reached.

some_function_that_may_fail <- function() {
if( runif(1) < .5 ) stop()
return(1)
}

r <- NULL
attempt <- 1
while( is.null(r) && attempt <= 3 ) {
attempt <- attempt + 1
try(
r <- some_function_that_may_fail()
)
}

How to retry after exception?

Do a while True inside your for loop, put your try code inside, and break from that while loop only when your code succeeds.

for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
break

Better way to retry a statement that threw an exception in vb.net

I think that's a bad usage, I use this one, and it's much cleaner.

Dim maxAttempt As Integer = 2

For i As Integer = maxAttempt To 0 Step -1

Try
...
'Successful Quit
Exit For

Catch
Thread.Sleep(2000)

End Try
Next

How do you implement a re-try-catch?

You need to enclose your try-catch inside a while loop like this: -

int count = 0;
int maxTries = 3;
while(true) {
try {
// Some Code
// break out of loop, or return, on success
} catch (SomeException e) {
// handle exception
if (++count == maxTries) throw e;
}
}

I have taken count and maxTries to avoid running into an infinite loop, in case the exception keeps on occurring in your try block.

Cleanest way to write retry logic?

Blanket catch statements that simply retry the same call can be dangerous if used as a general exception handling mechanism. Having said that, here's a lambda-based retry wrapper that you can use with any method. I chose to factor the number of retries and the retry timeout out as parameters for a bit more flexibility:

public static class Retry
{
public static void Do(
Action action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
Do<object>(() =>
{
action();
return null;
}, retryInterval, maxAttemptCount);
}

public static T Do<T>(
Func<T> action,
TimeSpan retryInterval,
int maxAttemptCount = 3)
{
var exceptions = new List<Exception>();

for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
try
{
if (attempted > 0)
{
Thread.Sleep(retryInterval);
}
return action();
}
catch (Exception ex)
{
exceptions.Add(ex);
}
}
throw new AggregateException(exceptions);
}
}

You can now use this utility method to perform retry logic:

Retry.Do(() => SomeFunctionThatCanFail(), TimeSpan.FromSeconds(1));

or:

Retry.Do(SomeFunctionThatCanFail, TimeSpan.FromSeconds(1));

or:

int result = Retry.Do(SomeFunctionWhichReturnsInt, TimeSpan.FromSeconds(1), 4);

Or you could even make an async overload.

How can you retry after an exception in Javascript when using promises?

Here's a sample retry function (not yet tested):

function retry(maxRetries, fn) {
return fn().catch(function(err) {
if (maxRetries <= 0) {
throw err;
}
return retry(maxRetries - 1, fn);
});
}

The idea is that you can wrap a function that returns a promise with something that will catch and retry on error until running out of retries. So if you're going to retry sendResponseAsync:

receiveMessageAsync(params)
.then(function(data)) {
return [data, handleMessageAsync(request)];
})
.spread(function(data, response) {
return [response, deleteMessageAsync(request)];
})
.spread(function(response, data) {
return retry(3, function () { return sendResponseAsync(response); });
})
.then(function(data) {
return waitForMessage(data);
})
.catch (function(err) {
// handle error here
});

Since the retry promise won't actually throw until all retries have been exhausted, your call chain can continue.

Edit:

Of course, you could always loop forever if you preferred:

function retryForever(fn) {
return fn().catch(function(err) {
return retryForever(fn);
});
}

What is the proper way to add retry loop to VBA code

Perhaps something like this...

    Option Explicit

Private Const MaxRetries As Long = 3

Public Function RunADO(strContext As String, strSQL As String, Optional intErrSilent As Integer = 0, Optional intErrLog = -1) As Integer
Dim attemptCounter As Long
For attemptCounter = 1 To MaxRetries
RunADO = RunADOInternal(strContext, strSQL, intErrSilent, intErrLog)
If RunADO = -1 Then
Exit Function
End If
If intErrSilent = 0 And attemptCounter >= MaxRetries Then
MsgBox Err.Number & ": " & Err.Description, vbCritical, "Run ADO"
RunADO = 0
Exit Function
End If
If intErrLog = -1 Then
PostErrorToLog Err.Number, strContext, Err.Source & ":" & Err.Description & ": " & "SQL: " & strSQL
End If
Application.Wait (Now + TimeValue("0:00:01"))
Next attemptCounter
End Function

Private Function RunADOInternal(strContext As String, strSQL As String, Optional intErrSilent As Integer = 0, Optional intErrLog = -1) As Integer
On Error GoTo ErrHandler

PostToLog strContext, "SQL: " & strSQL
CurrentProject.Connection.Execute strSQL, dbFailOnError
RunADO = -1
Exit Function
ErrHandler:
RunADO = 0
End Function

How to retry for loop when timeout error occurs: Where to add trycatch or withTimeout

Perhaps I'm missing something, but in the third example, using try(), you evaluate if(!is(df, 'try-error')) but a is the object that stores the results of try(). So shouldn't it be if(!is(a, 'try-error'))

files <- NULL
#sample.id <- NULL
for(i in 1:length(sample.id.path2[[1]])){
while(TRUE){
a <- try(as.data.frame(system(paste0("mcli ls s3/path/to/bucket/", sample.id.path2[['V2']][i], sep = ""), intern=TRUE)), silent=TRUE)
if(!is(a, 'try-error')) break
colnames(a)[1] <- "V1"
a$V1 <- gsub("^.{0,34}", "", a$V1)
a <- a %>% filter(str_detect(V1, 'fastq'))
}
#print(a)
b <- as.data.frame(paste0("", sample.id.path2[['V2']][i], sep = ""))
colnames(b)[1] <- "V1"
c <- as.data.frame(paste0(b$V1, a$V1, sep = ""))
colnames(c)[1] <- "V2"
d <- cbind(a,c)
print(d)
files <- rbind(files, d)
}


Related Topics



Leave a reply



Submit