Is it possible to use Spring RestTemplate without using Exceptions to handle http response with status 500?
RestTemplate restTemplate = new RestTemplate();
try {
response = restTemplate.getForEntity(probe.getUrl(), String.class);
boolean isOK = response.getStatusCode() == HttpStatus.OK;
// would be nice if 500 would also stay here
}
catch (HttpServerErrorException exc) {
// but seems only possible to handle here...
}
You can create a controller using annotation @ControllerAdvice
if you using springmvc. In the controller write:
@ExceptionHandler(HttpClientErrorException.class)
public String handleXXException(HttpClientErrorException e) {
log.error("log HttpClientErrorException: ", e);
return "HttpClientErrorException_message";
}
@ExceptionHandler(HttpServerErrorException.class)
public String handleXXException(HttpServerErrorException e) {
log.error("log HttpServerErrorException: ", e);
return "HttpServerErrorException_message";
}
...
// catch unknown error
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
log.error("log unknown error", e);
return "unknown_error_message";
}
and the DefaultResponseErrorHandler
throw these two kinds of exceptions:
@Override
public void handleError(ClientHttpResponse response) throws IOException {
HttpStatus statusCode = getHttpStatusCode(response);
switch (statusCode.series()) {
case CLIENT_ERROR:
throw new HttpClientErrorException(statusCode, response.getStatusText(),
response.getHeaders(), getResponseBody(response), getCharset(response));
case SERVER_ERROR:
throw new HttpServerErrorException(statusCode, response.getStatusText(),
response.getHeaders(), getResponseBody(response), getCharset(response));
default:
throw new RestClientException("Unknown status code [" + statusCode + "]");
}
}
and you can use:e.getResponseBodyAsString();
,e.getStatusCode();
blabla in the controller advice to get response message when the exceptions occurs.
Not tested, but you could simply use a custom ResponseErrorHandler
that is not a DefaultResponseErrorHandler
, or that extends DefaultResponseErrorHandler but overrides hasError()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With