title: Spring boot rest api: how to respond gracefully if Request Body is sent in incorrect format?
body: <p>Let's say we have Spring boot api endpoint:</p>
  
  <p><strong>Controller</strong></p>
  
  <pre><code>...
  public String registerUser(@RequestBody @Valid User user) {
     ...
  }
  </code></pre>
  
  <p><strong>User</strong></p>
  
  <pre><code>class User {
     @NotNull
     private Integer age;
  
     @NotNull
     private String name; 
     ...
  }
  </code></pre>
  
  <p>When I send a request with a missing field, for example, <code>age</code> spring respond with a nice message explaining that <code>age</code> param is missing with property path, something like:</p>
  
  <pre><code>{
    "timestamp": "2016-12-20T18:44:29.450+0000",
    "status": 400,
    "error": "Bad Request",
    "exception": "org.springframework.web.bind.MethodArgumentNotValidException",
    "errors": [
      {
        "defaultMessage": "may not be nullt",
        "objectName": "user",
        "field": "age",
        ...
  </code></pre>
  
  <p>But if I provide <code>age</code> param as String in a request:</p>
  
  <pre><code>{
     age: "somestring"
  }
  </code></pre>
  
  <p>I get <code>org.springframework.http.converter.HttpMessageNotReadableException</code> ... <code>Could not read document: Can not deserialize value of type java.lang.Integer from String</code> with information in which method, line this exception occurred (Which I do not want to reveal).</p>
  
  <p>But is there any way to respond such an exception in a format like missing age?</p>
  
  <p>Something like:</p>
  
  <pre><code>"errors": [
          {
            "defaultMessage": "incorrect format",
            "objectName": "user",
            "field": "age",
            ...
  </code></pre>