Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Rest Client want to see error message instead of exception

I have a spring rest client. when authentication details are not provided in the headers and I hit the service with

ResponseEntity<String> resp = restTemplate.exchange(url, HttpMethod.GET, request, String.class);

I get exception :

invoking error handler Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 Unauthorized at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)

But when I hit the url on mozilla browser, I get message like

{"errors":[{"code":"xxxx","reason":"xxxx"}]}

Now here is what i want: i want to capture this error message in my code instead of getting 401 exception. I tried to see if there is anything in the response. But the response received is null. How can I capture the error message received from the webservice ?

like image 868
Amar Avatar asked Oct 16 '14 12:10

Amar


1 Answers

I feel odd to post answer for my own question. But i finally achieved it through the following...

} catch (HttpClientErrorException e) {
      System.out.println(e.getStatusCode());
      System.out.println(e.getResponseBodyAsString());
    }

I was incorrectly searching for errors in response entity. But it is available in the exception.

like image 50
Amar Avatar answered Nov 15 '22 18:11

Amar