Proper way to parse the body of an error with Spring's RestTemplate

Viewed 1972

I'm using the @Valid annotation on the @RequestBody argument which uses Hibernate Validation, to ensure it's validated:

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

Following the recommendations of the Spring Rest book, I'm catching that exception and turning it into a nice JSON error message that looks like this:

{
  "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"
      }
    ]
  }
}

On the client side, I'm doing this to make the call:

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

Using Object until I define exactly on the representation of the response. When there's a validation error though, I get a 400 error which throws a HttpClientErrorException.

HttpClientErrorException has a getResponseBodyAsString() that responds with the JSON I pasted above. I could manually parse it, but I was wondering what's the most correct way to parse it. RestTemplate clearly has a mechanism for automatically parsing responses when there's no errors. Does it have something for errors?

0 Answers
Related