title: How to return a proper validation error for enum types in Spring Boot?
body: <p>I have created a demo spring boot application. The request takes in a car object and returns the same. I am trying to figure out a way to send a proper message to the user if the carType is not a valid enum.</p>
  <p>Request</p>
  <pre><code>{
      &quot;carType&quot;: &quot;l&quot;
  }
  </code></pre>
  <p>Response</p>
  <pre><code>{
      &quot;message&quot;: &quot;JSON parse error: Cannot deserialize value of type `com.example.demo.Car$CarType` from String \&quot;l\&quot;: not one of the values accepted for Enum class: [Racing, Sedan]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.example.demo.Car$CarType` from String \&quot;l\&quot;: not one of the values accepted for Enum class: [Racing, Sedan]\n at [Source: (PushbackInputStream); line: 2, column: 13] (through reference chain: com.example.demo.Car[\&quot;carType\&quot;])&quot;,
      &quot;statusCode&quot;: &quot;BAD_REQUEST&quot;
  }
  </code></pre>
  <p>How can I send a proper message to the user without displaying the class names and the stack trace? I want the user to know what are the valid types of enum but do not want the message to have java error trace. Is there a way to extract proper message having just the field that is erroneous. What is the standard way of validating enums?</p>
  <p><strong>Car.java</strong></p>
  <pre><code>import lombok.*;
  
  @Getter
  @Setter
  public class Car {
       enum CarType {
          Sedan,
          Racing
      }
  
      CarType carType;
  }
  
  </code></pre>
  <p><strong>DemoControllerAdvice.java</strong></p>
  <pre><code>import org.springframework.http.HttpStatus;
  import org.springframework.http.converter.HttpMessageNotReadableException;
  import org.springframework.web.bind.annotation.ExceptionHandler;
  import org.springframework.web.bind.annotation.ResponseStatus;
  import org.springframework.web.bind.annotation.RestControllerAdvice;
  
  @RestControllerAdvice
  public class DemoControllerAdvice {
  
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      @ExceptionHandler(HttpMessageNotReadableException.class)
      public ErrorObject handleJsonErrors(HttpMessageNotReadableException exception){
  
          return new ErrorObject(exception.getMessage(), HttpStatus.BAD_REQUEST);
      }
  }
  
  </code></pre>
  <p><strong>DemoController.java</strong></p>
  <pre><code>@RestController
  public class DemoController {
  
      @PostMapping(&quot;/car&quot;)
      public Car postMyCar(@RequestBody Car car){
          return car;
      }
      
  }
  </code></pre>
  <p>Is there any neat way to achieve using Hibernate Validator but without using a custom hibernate Validator like in the answer below?
  <a href="https://stackoverflow.com/questions/18205787/how-to-use-hibernate-validation-annotations-with-enums">How to use Hibernate validation annotations with enums?</a></p>