简体   繁体   中英

Nested try/catch inside block and PMD rule

I'm trying to refactor this code cause PMD throwing Failure:PreserveStackTrace:3, the main problem is how I can collapse exception e1 into e2, is it anti-pattern right now? I thinking about extract second try or put it into finally but it might cause problems with bussiness logic.

Code:

        try {
            try {
                response = paypal.execute(params);
            } catch (final FailedConnectionAttempException e1) {
                log.warn("The first attempt is failed " + " Tryin again ", e1);

                try {
                    response = paypal.execute(params);
                } catch (final FailedConnectionAttempException e2) {
                    throw new PaymentException("The second attempt failed ", e2);
                }
            }
        } catch (final IntegrationException e) {
            throw new PaymentException("Unable to execute ", e);
        }
    }

I'm assuming you are using the Apache HttpClient because I recognize the execute method.

You can use the HttpRequestRetryHandler to configure retry behavior instead of handling with that catch block.

HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
    @Override
    public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
        return executionCount < 5;
    }
};
HttpClient client = HttpClientBuilder.create()
        .setRetryHandler(retryHandler)
        .build();

Also I should also mention, HttpClient will retry a failed request 3 times by default and I notice in your exceptions it says first/second attempt, in reality it is the first 4 attempts and the first 7 attempts, so you can consider how many retries you really need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM