Kramer
Kramer

Reputation: 1058

How to handle error responses using spring rest client

I am trying to better handle bad responses when using the sprint rest client. My code is as follows:

ResponseEntity<Foo> response = null;

try {
    response = restTemplate.exchange(uri, HttpMethod.GET,
                       new HttpEntity<>(new HttpHeaders()), Foo.class);
catch (RestClientException rce) {
    //what to do here?
} 

This works great as long as there is no error. The problem is that when the corresponding web service returns an error (or times out), I just get an exception. There is no enum with a status code where I could handle it as I wish. Sometimes the error message is useful. Sometimes not. Usually, if the corresponding server returns an html error page, I just get a message that the object cannot be created, but the specific error is swallowed.

Any ideas?

Upvotes: 2

Views: 3245

Answers (2)

Xeon
Xeon

Reputation: 5989

What can you get with rce.getMostSpecificCause()? Maybe there is some more information.

You can catch HttpStatusCodeException that is direct subclass of RestClientException which is more generic. There are a lot of exceptions that you can catch that are much more specific than RestClientException e.g.

public class HttpServerErrorException
extends HttpStatusCodeException

Exception thrown when an HTTP 5xx is received.

Look at the docs for RestClientException.

Upvotes: 1

Leo Rohr
Leo Rohr

Reputation: 196

If the website you are querying returns an HTTP errorstatus then that should be reflected in the response object and you can switch through the statuses that you want to cover.

switch(response.getStatus()) {
  case HTTPStatus.BAD_REQUEST: {
  }
  case HTTPStatus.BAD_GATEWAY: {
  }
...
}

The RestClientException should only be thrown if there is a client side error, i.e. that's independent from the server response. (Spring Doc)

Upvotes: 0

Related Questions