3

我正在开发一个连接到 Web 服务的 Android 应用程序。从网络服务我得到这个错误:

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

我正在使用适用于 Android 的 SpringFramework Rest Client,并使用以下代码连接到 Web 服务:

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;
}

但是,Web 服务也返回一个像这样的 JSON 字符串:

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

即使我得到一个例外,我怎么能得到它?

4

2 回答 2

2

你应该抓住RestClientException这样的:

  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
     }

  }

RestTemplate查看,的 javadocs RestClientException

于 2013-06-27T08:49:07.253 回答
0

我对此的方法是添加一个多重捕获,以确保处理每个单独的错误。

还要注意:

  1. 您记录的内容是因为响应是转义的 Java 字符(例如:/u733),因此您可以使用StringEscapeUtils.unescapeJava(),如下例所示

  2. 由于您必须处理有问题的响应(可以说不稳定),因此还可以捕获HttpMessageNotReadableException,当响应中存在意外对象时会发生这种情况。

try {
          return restTemplate.postForObject(url, request, responseType, uriVariables);
      }catch(HttpStatusCodeException e) {
          String errorResponse = e.getResponseBodyAsString();
          LOG.error("RestResponse: {}", StringEscapeUtils.unescapeJava(errorResponse));
          throw e;
      } catch (HttpMessageNotReadableException e) {
          LOG.error("Unexpected object in the response", e);
          throw e;
      }catch (Exception e){
          LOG.error("Unexpected error", e);
          throw new InvalidDataException("Unexpected error");
      }
于 2019-08-07T13:51:44.907 回答