Search code examples
javaspringexceptionresttemplate

RestTemplate: Custom Exception thrown from ResponseErrorHandler is NOT Propagating to Caller


I am developing an API. Going by Clean Code and other clean programming guidelines, I do not want to clutter my code with try/catch blocks. However I am facing a challenge: a custom Exception thrown from ResponseErrorHandler is not propagating to the caller; instead it is ResourceAccessException that the caller receives.

Here is my API code (irreverent part is omitted for brevity). Note I am not surrounding restTemplate.delete() call in a try block - that is intentional:

restTemplate.setErrorHandler(ecmResponseErrorHandler);
restTemplate.delete(serviceUrl, params);

My ecmResponseErrorHandler code (irreverent part is omitted for brevity):

public class ECMResponseErrorHandler implements ResponseErrorHandler {

    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        if (response.getStatusCode() != HttpStatus.OK) {
            //logging etc.
            return true;
        }
        return false;
    }

    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
       //appropriately populate ECMException() and then throw it
       throw new ECMException();
    }
}

My ECMException is (irreverent part is omitted for brevity):

public class ECMException extends IOException {

    public ECMException() {
        super();
    }
    //etc.

 }

Now, instead of receiving ECMException, my JUnit test case receives ResourceAccessException:

java.lang.Exception: Unexpected exception, expected<com.db.dbbpm.ecmfacade.exception.ECMException> but was<org.springframework.web.client.ResourceAccessException>

Everything works fine if I change my API code to below; however I don't want to clutter my API code with try/catch blocks:

restTemplate.setErrorHandler(ecmResponseErrorHandler);
try {
    restTemplate.delete(serviceUrl, params);
} catch () {
    throw new ECMException();
}

Why is the ECMException thrown from ResponseErrorHandler not propagating up all the way to caller? How do I make it happen?


Solution

  • Making ECMException extend RuntimeException (instead of IOException) solved the problem. Now my code is much cleaner.

    public class ECMException extends RuntimeException {
    
        public ECMException() {
            super();
        }
        //etc.
    }