12

I am using spring RestTemplate to consume rest services(exposed in spring rest). I am able to consume success scenarios. But for negative scenarios, service returns error messages and error codes. I need to show those error messages in my web page.

For e.g. for invalid request, service throws HttpStatus.BAD_REQUEST with proper messages. If i put try-catch block it goes to catch block and I am not able to get ResponseEntity object.

try {
    ResponseEntity<ResponseWrapper<MyEntity>> responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, entity,
        new ParameterizedTypeReference<ResponseWrapper<MyEntity>>() {
    });
    responseEntity.getStatusCode();
    } catch (Exception e) {
        //TODO How to get response here, so that i can get error messages?
        e.printStackTrace();
    }

How to get ResponseWrapper for exception case?

I read about CustomRestTemplate and ResponseExtractor from here but could not decide which one is best for my case.

Community
  • 1
  • 1
Abhendra Singh
  • 1,959
  • 4
  • 26
  • 46
  • you can create new Response Entity object itself. new ResponseEntity(HttpStatus.BAD_REQUEST); for getting error messages , you need to catch RestClientException and get message by rce.getMessage() something like that. – anurag gupta Feb 25 '15 at 04:22
  • 1
    You can catch HttpStatusCodeException that has the status code http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/HttpStatusCodeException.html – Lionel Port Feb 25 '15 at 04:32
  • You can visit bellow thread. It has full working code with description: https://stackoverflow.com/a/51805956/3073945 – Md. Sajedul Karim Aug 12 '18 at 05:34

2 Answers2

19

I found solution. HttpClientErrorException worked for me.

It has e.getResponseBodyAsString() function which returns ResponseBody.

Abhendra Singh
  • 1,959
  • 4
  • 26
  • 46
8

You might want to distinguish between:

HttpClientErrorException (HTTP-Status >=400) or HttpServerErrorException (HTTP-Status >= 500) or even RestClientException.

Further on there is a good doc about defining your own ErrorHandler, see this link

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
phirzel
  • 139
  • 2
  • 5