I’m working on a script which continually monitors a set of files to ensure that they’re no more than four hours old. During the time when these files are being copied, they may be seen as missing by the script, so I’m manually retrying once inside of a try…catch… block. E.g.:
try
{
report.age = getFileAgeInMilliSeconds(report.filePath);
// If the file is over age threshhold.
if ( report.age > REPORT_AGE_THRESHOLD )
{
// Generate an alert and push it onto the stack.
downtimeReportAlerts.push(generateOldFileAlert(report));
}
}
// If we have trouble...
catch (e)
{
// Find out what the error was and handle it as well as possible.
switch (e.number)
{
case FILE_NOT_FOUND_ERROR_CODE:
// Try once more.
WScript.Sleep(FILE_STAT_RETRY_INTERVAL);
try
{
report.age = getFileAgeInMilliSeconds(report.filePath);
// If the file is over age threshhold.
if ( report.age > REPORT_AGE_THRESHOLD )
{
// Generate an alert and push it onto the stack.
downtimeReportAlerts.push(generateOldFileAlert(report));
}
}
// If we have trouble this time...
catch (e)
{
switch (e.number)
{
case FILE_NOT_FOUND_ERROR_CODE:
// Add an alert to the stack.
downtimeReportAlerts.push(generateFileUnavailableAlert(report));
break;
default:
// No idea what the error is. Let it bubble up.
throw(e);
break;
}
}
break;
default:
// No idea what the error is. Let it bubble up.
throw(e);
break;
}
}
Are there any established patterns for retrying an operation in this type of scenario? I was thinking of trying to rewrite this into a recursive function, since there’s a lot of duplicate code where errors could creep in here, but I wasn’t sure how and thought I’d check if there’s a better solution first.
A recursive method that attempts to perform the push would most likely be the way to go, still utilizing a try..catch to retry the recursive method (perhaps even still with a “sleep” involved and any other specific error handling). I would introduce a RETRY_COUNT constant defining how many times it should be called recursively so it does not get into a continuous loop if no other error is encountered and just increment an “attemptCount” variable to keep track of how many times it has attempted to execute so you can break out of the loop after it reaches the RETRY_COUNT.