捕获后重试

时间:2017-07-14 05:33:41

标签: java fortify retry-logic

这是我使用的逻辑:

int retries = config.get("retries");
Response resp = null
do {
    try {
        resp = operation.execute();
        retries = 0;
    } catch (Exception ex) { //Note. Please excuse this catch pattern. Its not a problem now.
        if isAParticularException(ex) { //call a method to check the wrapped exception and other details
            retries--;
            LOGGER.info("Integrity exception, can be retried");
            if (retries == 0) {
                LOGGER.info("Retry exhausted");
                throw ex;
            }
            LOGGER.info("Retrying operation, retry count " + ledgerRetry);
        } else {
            throw ex;
        }
    }
} while (retries > 0);
return resp;

重试次数也在考虑原始操作。但问题就是那个

  1. 如果我直接从try块返回而没有分配任何东西,那么SCA(Fortify for me)报告没有读取变量重试(在成功流程中),并且
  2. 如果我分配并按上述方式执行,那么SCA就会立即大声疾呼 将值重新分配给retries变量,甚至不读取 它。
  3. 考虑:

    1. 第一次调用应该独立于我们读取的任何值 '重试'
    2. 应避免重复代码,避免递归 也很好。
    3. 可能是一件简单的事情,但我可能并没有抓住它。请建议。

1 个答案:

答案 0 :(得分:0)

为什么不使用break而不是将重试设置为0?我猜你在执行操作后设置重试,因为你想要打破执行循环:

int retries = config.get("retries");
Response resp = null

do {
    try {
        resp = operation.execute();
        break;
    } catch (Exception ex) {
        if isAParticularException(ex) { //call a method to check the wrapped exception and other details
            retries--;
            LOGGER.info("Integrity exception, can be retried");
            if (retries == 0) {
                LOGGER.info("Retry exhausted");
                throw ex;
            }
            LOGGER.info("Retrying operation, retry count " + ledgerRetry);
        } else {
            throw ex;
        }
    }
} while (retries > 0);
return resp;

或者如果你想要你可以在try catch中返回resp,如果没有执行任何操作则返回null:

int retries = config.get("retries");
Response resp = null

do {
    try {
        resp = operation.execute();
        return resp;
    } catch (Exception ex) {
        if isAParticularException(ex) { //call a method to check the wrapped exception and other details
            retries--;
            LOGGER.info("Integrity exception, can be retried");
            if (retries == 0) {
                LOGGER.info("Retry exhausted");
                throw ex;
            }
            LOGGER.info("Retrying operation, retry count " + ledgerRetry);
        } else {
            throw ex;
        }
    }
} while (retries > 0);
return null;

如果我是你,我会考虑抛出异常而不是返回null。