I have a rest service which send an 404 error when the resources is not found. Here the source of my controller and the exception which send Http 404.
@Contr
Since it's 2018 and I hope that when people say "Spring" they actually mean "Spring Boot" at least, I wanted to expand the given answers with a less dust-covered approach.
Everything mentioned in the previous answers is correct - you need to use a custom ResponseErrorHandler
.
Now, in Spring Boot world the way to configure it is a bit simpler than before.
There is a convenient class called RestTemplateBuilder
. If you read the very first line of its java doc it says:
Builder that can be used to configure and create a RestTemplate. Provides convenience methods to register converters, error handlers and UriTemplateHandlers.
It actually has a method just for that:
new RestTemplateBuilder().errorHandler(new DefaultResponseErrorHandler()).build();
On top of that, Spring guys realized the drawbacks of a conventional RestTemplate
long time ago, and how it can be especially painful in tests. They created a convenient class, TestRestTemplate
, which serves as a wrapper around RestTemplate
and set its errorHandler to an empty implementation:
private static class NoOpResponseErrorHandler extends
DefaultResponseErrorHandler {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
}