Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Rest Client Exception Handling

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.

like image 949
Abhendra Singh Avatar asked Feb 25 '15 04:02

Abhendra Singh


People also ask

How do you catch a RestTemplate exception?

Default Error Handling By default, the RestTemplate will throw one of these exceptions in the case of an HTTP error: HttpClientErrorException – in the case of HTTP status 4xx. HttpServerErrorException – in the case of HTTP status 5xx. UnknownHttpStatusCodeException – in the case of an unknown HTTP status.

What is REST client exception?

RestClientException(java.lang.String pMessage) A constructor which takes a message, response object and error code. RestClientException(java.lang.String pMessage, java.lang.Throwable pCause) A constructor which takes a source exception, response object and error code.

Does spring provide exception handling?

Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.


2 Answers

I found solution. HttpClientErrorException worked for me.

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

like image 60
Abhendra Singh Avatar answered Oct 03 '22 05:10

Abhendra Singh


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

like image 42
phirzel Avatar answered Oct 03 '22 04:10

phirzel