Java 捕获后重试
以下是我使用的逻辑:Java 捕获后重试,java,fortify,retry-logic,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 isAP
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;
重试次数也将考虑原始操作。但问题是
可能是件简单的事,但我可能没有领会。请建议。为什么不使用中断而不是将重试次数设置为0?我猜您在操作execute之后设置了重试,因为您想中断执行循环:
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。
而不是捕获每个<代码>异常< /代码>,然后测试它是否是特定的,直接捕获特定的代码。代码>捕获(SpecificException ex)它检查封装在通用异常中的特定异常。由于许多其他方法都使用它,所以它是用一个方法编写的。顺便说一句,这不是Foritfy问题解决方案的主要关注点。在这两个代码段中,SCA都会抱怨变量retries
没有被使用。我不确定这是否是一个好的做法,但如果retries小于0,可以将retries设置为0,并使用while循环而不是do while,并检查重试次数是否>=0不确定:-)这让我难以置信,因为重试值不是硬编码的。但我认为这不是一个好的做法。因为对于错误的值,它不会运行。这意味着我有两个相同的检查。如果有人设置retries为Integer.MIN_值怎么办?如果执行重试,则会有Integer.MAX_值,while(retries>0)将为true