0

这是我使用的逻辑:

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)报告未读取变量 retries(在成功流程中),并且
  2. 如果我按上述方式分配和执行,则 SCA 会大声疾呼立即将值重新分配给 retries 变量,甚至无需读取它。

注意事项:

  1. 第一次调用应该独立于我们为“重试”读取的任何值
  2. 应该避免重复代码,避免递归也很好。

可能是一件简单的事情,但我可能没有抓住它。请建议。

4

1 回答 1

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。

于 2017-07-14T05:57:56.080 回答