Daria Daria - 3 years ago 283
Java Question

Spring RestTemplate handle custom status code

I should call some service from my application that can return unusual http status codes, such as 230, 240 etc. By default error handler I'm getting:

Servlet.service() for servlet [dispatcher] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.UnknownHttpStatusCodeException: Unknown status code [230] null] with root cause...


When I use my custom error handler I can avoid this:

@Override
public boolean hasError(ClientHttpResponse response) throws IOException {

int status = response.getRawStatusCode();
if (status >= 200 && status <= 299)
return false;

HttpStatus statusCode = response.getStatusCode();
if (statusCode.is2xxSuccessful())
return false;
HttpStatus.Series series = statusCode.series();
return (HttpStatus.Series.CLIENT_ERROR.equals(series)
|| HttpStatus.Series.SERVER_ERROR.equals(series));
}


But when RestTmplate tries to retrieve it falls into the same exception in
MessageBodyClientHttpResponseWrapper
:

public boolean hasMessageBody() throws IOException {
HttpStatus responseStatus = this.getStatusCode();
if (responseStatus.is1xxInformational() || responseStatus == HttpStatus.NO_CONTENT ||
responseStatus == HttpStatus.NOT_MODIFIED) {
return false;
}
else if (this.getHeaders().getContentLength() == 0) {
return false;
}
return true;
}


How can I get response body correctly?

Answer Source

Finally, issue solved in Spring 5, tested it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download