how do i return validation errors for enum types in spring boot?

No. The de-serialisation happens before the validation.

If you want Hibernate to do it, then you already linked to the answer. Otherwise you’ll have to handle the exception yourself.

private static final Pattern ENUM_MSG = Pattern.compile("values accepted for Enum class: \[([^\]])\]);"

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public ErrorObject handleJsonErrors(HttpMessageNotReadableException exception){
    if (exception.getCause() != null && exception.getCause() instanceof InvalidFormatException) {
        Matcher match = ENUM_MSG.matcher(exception.getCause().getMessage());
        if (match.test()) {
            return new ErrorObject("value should be: " + match.group(1),  HttpStatus.BAD_REQUEST);
        }
    }

    return new ErrorObject(exception.getMessage(), HttpStatus.BAD_REQUEST);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top