Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 885
Siva Avatar asked Nov 03 '25 22:11

Siva


1 Answers

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

like image 83
Flood2d Avatar answered Nov 06 '25 13:11

Flood2d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!