2

I develop a Spring Boot project and I use ExceptionHandler to catch all exceptions with @RestControllerAdvice annotation. There is no problem on Server side to catch exception. However, I don't know how to catch these exceptions in client application.

Could you help me please ?

4
  • What client are you using? RestTemplate? Commented Jul 24, 2017 at 14:57
  • yes it s RestTemplate Commented Jul 25, 2017 at 8:32
  • Then just use try - catch block when using RestTemplate. Catch RestClientException and handle it as needed. Commented Jul 25, 2017 at 8:40
  • Thanks Gondy, it will work : ) Commented Jul 25, 2017 at 8:56

2 Answers 2

2

If you're using spring-web's RestTemplate, here's an example:

try { ResponseEntity<String> response = new RestTemplate().getForEntity(url, String.class); System.out.println("Response: " + response.getBody()); } catch (HttpStatusCodeException e) { System.err.println("Problem querying " + url + ". " + "Status code " + e.getStatusCode() + " and error message " + e.getResponseBodyAsString()); } 

Note that RestTemplate throws an exception by default for error status codes, so you need to catch HttpStatusCodeException.

Not all errors are HttpStatusCodeException though, but all of them have RestClientException as parent and you can also catch it if really needed.

Sign up to request clarification or add additional context in comments.

Comments

0

On the client side you are, presumably, using a HTTP client (such as Spring's RestTemplate or Apache Commons' HttpClient). Something like this, perhaps:

ResponseEntity<String> response = restTemplate.getForEntity(url, String.class); 

Given this code, the HTTP status and the response body are available as follows:

HttpStatus httpStatus = response.getStatusCode(); String responseBody = response.getBody(); 

So, whatever status code and response body you supplied via your RestControllerAdvice can be read out of the response.

A typical approach would be to assess whether the HttpStatus is a 200 and if it is not then fall into an exception handling block, using the response body to understand the nature of the exception.

1 Comment

Thanks Glitch, your solution saves my day.