Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get web service message when I get 422 error using SpringFramework Android Rest Client

I'm developing an Android application that connects to a Web service. From the web service I get this error:

POST request for "xxx" resulted in 422 (Unprocessable Entity); invoking error handler

I'm using SpringFramework Rest Client for Android, and I connect to the web service with this code:

public static User sendUserPersonalData(User userProfileData)
{
    try
    {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
        HttpEntity<User> requestEntity = new HttpEntity<User>(userProfileData, requestHeaders);

        GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(messageConverter);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setReadTimeout(readTimeout);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setMessageConverters(messageConverters);

        String url = URL_BASE_WEB + USER_PERSONAL_DATA_CALL;
        ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, User.class);

        return responseEntity.getBody();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}

But, the web service also returns a JSON string like this one:

{
    "email": [
        "is invalid"
    ],
    "birthday": [
        "is invalid"
    ],
    "startday": [
        "is invalid"
    ],
    "sex_preference": [
        "can't be blank"
    ],
    "password": [
        "is too long (maximum is 4 characters)"
    ]
}

How can I get it even if I get an Exception?

like image 223
VansFannel Avatar asked Sep 09 '26 04:09

VansFannel


1 Answers

You should catch the RestClientException like this :

  try{
     ....
     restTemplate.exchange(...);
  }catch(RestClientException e){
     //process exception
     if(e instanceof HttpStatusCodeException){
         String errorResponse=((HttpStatusCodeException)e).getResponseBodyAsString();
         //now you have the response, construct json from it, and extract the errors
     }

  }

Have a look at the javadocs for RestTemplate, RestClientException.

like image 191
Ovidiu Latcu Avatar answered Sep 11 '26 08:09

Ovidiu Latcu



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!