Handling subclasses of HttpServerErrorException using @Retryable

Viewed 31

I am using spring batch.Sometimes, I get 502 Http response. Below is the exception message I get:

Error finding details for ids [123, 456 ] due to I/O error on POST request for \""http://localhost:18080/my/api/path/findByIds\"": localhost:18080 failed to respond; nested exception is org.apache.http.NoHttpResponseException: localhost:18080 failed to respond "",""level"":""err"",""thread"":""taskExecutor-1"",""logClass"":""c.t.k.e.r.myRepository"",""logMethod"":""findPersonByIds"",

Whatever the error from server side is wrapped up in HttpServerErrorException . I had look at this exception class . BadGateway is a subclass of HttpServerErrorException. I have two different use cases(in separate projects I am working on).

a)I have to retry only when a BadGateway exception occurs.

b)Whenever BadGateway and the exception body contains NoHttpResponseException , I need to retry(use case 2 in a different project)

I have tried something like this but has not worked .

@Retryable(value = NoHttpResponseException.class)
myMethod()

How can I achieve this?

1 Answers

You can create a component (or bean) that will allow you to perform the custom logic on the root exception and reference it in the @Retryable annotation. Any exceptions thrown will call the shouldRetry() method

@Component
public class ExceptionChecker {

    public boolean shouldRetry(Throwable t) {
        // perform logic on exception to check if retry is required
        return true;
    }
}

// Use the name of the component (exceptionChecker in this case) in the annotation
// and pass the exception to the shouldRetry method

@Retryable(exceptionExpression = "@exceptionChecker.shouldRetry(#root)")
public String retryableMethod(String name) {
Related