是否有任何推荐的重试操作模式?

时间:2011-09-23 17:32:46

标签: design-patterns

我正在编写一个脚本,该脚本会持续监视一组文件,以确保它们不会超过四个小时。在复制这些文件的过程中,脚本可能会看到它们丢失,所以我在try ... catch ...块中手动重试一次。 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;
        }
    }

在这种情况下是否有重建操作的既定模式?我正在考虑尝试将其重写为一个递归函数,因为有很多重复的代码,其中错误可能会在这里蔓延,但我不知道如何并且认为我先检查是否有更好的解决方案。

1 个答案:

答案 0 :(得分:3)

尝试执行推送的递归方法很可能是要走的路,仍然使用try..catch重试递归方法(可能甚至还涉及“睡眠”和任何其他特定的错误处理) 。我将引入一个RETRY_COUNT常量,定义它应该递归调用多少次,这样如果没有遇到其他错误,它就不会进入连续循环,只是递增一个“attemptCount”变量来跟踪它尝试执行的次数。所以你可以在达到RETRY_COUNT之后突破循环。