Siva
Siva

Reputation: 3327

How to get responseBody from Java Exception

While calling the REST service, Its giving HttpClientErrorException, I'm able to retrieve status code and error message, but how can I get responseBody ?

I'm trying the bellow code, but unable to typecast to HttpResponse.

catch(HttpClientErrorException e) {  
   // I am trying to typecast to HttpResponse, but its throwing error
     HttpResponse response = (HttpResponse) e;
     String msg = response.getEntity().getContent().toString(); 
}

What am I doing wrong ? Can anyone please suggest?

Upvotes: 4

Views: 12761

Answers (1)

Flood2d
Flood2d

Reputation: 1358

HttpClientErrorException extends RestClientResponseException which contains the method getResponseBodyAsString().

So it's a mistake to cast it to HttpResponse, in fact HttpClientErrorException doesn't extend HttpResponse

Simply do this

catch(HttpClientErrorException e){  
     String body = e.getResponseBodyAsString();
}

For more info http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/HttpClientErrorException.html

Upvotes: 7

Related Questions