捕获后重试

问题描述 投票:0回答:1

这是我使用的逻辑:

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就会立即将值重新分配给重试变量,而不会读取它。

注意事项:

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

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

java fortify retry-logic
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。

© www.soinside.com 2019 - 2024. All rights reserved.