用Spring的RestTemplate

时间:2017-09-13 23:36:27

标签: java json spring resttemplate

我在使用Hibernate验证的@Valid参数上使用@RequestBody注释,以确保它已经过验证:

public ResponseEntity<?> register(@RequestBody @Valid RegistrationModel registration) { ...

按照Spring Rest一书的建议,我正在捕获该异常并将其转换为一个好的JSON错误消息,如下所示:

{
  "title": "Validation Failed",
  "status": 400,
  "detail": "Input validation failed",
  "timeStamp": 1505345551757,
  "developerMessage": "org.springframework.web.bind.MethodArgumentNotValidException",
  "errors": {
    "hashedPassword": [
      {
        "code": "NotNull",
        "message": "must not be null"
      }
    ],
    "organization": [
      {
        "code": "NotBlank",
        "message": "must not be blank"
      }
    ],
    "name": [
      {
        "code": "NotBlank",
        "message": "must not be blank"
      }
    ]
  }
}

在客户端,我这样做是为了打电话:

Object result = restTemplate.postForObject("http://localhost:8080/v1/registration", registration, Object.class);

使用Object直到我完全定义响应的表示。但是当出现验证错误时,我会收到400错误,该错误会引发HttpClientErrorException

HttpClientErrorException有一个getResponseBodyAsString(),可以使用上面粘贴的JSON进行响应。我可以手动解析它,但我想知道解析它的方法是什么正确的。 RestTemplate显然有一种机制,可以在没有错误时自动解析响应。它有错误吗?

0 个答案:

没有答案
相关问题