I am calling a ReST
service through RestTemplate
and trying to override ResponseErrorHandler
in Spring 3.2
to handle custom error codes.
CustomResponseErrroHandler
public class MyResponseErrorHandler implements ResponseErrorHandler {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
boolean hasError = false;
int rawStatusCode = response.getRawStatusCode();
if (rawStatusCode != 200){
hasError = true;
}
return hasError;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
//String body = IOUtils.toString(response.getBody());
throw new CustomServiceException(response.getRawStatusCode() , "custom Error");
}
}
Spring
framework invokes hasError
method but not handleError
, so I couldn't throw my custom exception. After delving into Spring
RestTemplate
source code, I realized that the code in handleResponseError
method is causing the issue - It is looking for response.getStatusCode
or response.getStatusText
and throwing exception (as statusCode/statusText is null when Rest
service throws exception) and it never calls either custom implemented or default handleError
method in the next line.
Spring
RestTemplate
source code for handleResponse
method:
private void handleResponseError(HttpMethod method, URI url, ClientHttpResponse response) throws IOException {
if (logger.isWarnEnabled()) {
try {
logger.warn(method.name() + " request for \"" + url + "\" resulted in " +
response.getStatusCode() + " (" + response.getStatusText() + "); invoking error handler");
}
catch (IOException e) {
// ignore
}
}
getErrorHandler().handleError(response);
}
FYI, while service throws exception, I can read rawstatuscode but not statuscode from response
How to bypass this framework code and make call my custom handler? Thanks for your help in advance.