Spring Boot BindingResult returns 2 same error messages on one field

Viewed 37

I tried using annotation @NotNull and @Past with my field for validation, but when I posted with null value in PostMan, it gave me 2 error responses instead of 1, is this a problem and if it is, how to fix it?

Error Handler:

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(final MethodArgumentNotValidException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
    logger.info(ex.getClass().getName());

    final Map<String, String> errors = new HashMap<>();

    for (final FieldError error : ex.getBindingResult().getFieldErrors()) {
        errors.put(error.getField(), String.format("%s %s", error.getField(), error.getDefaultMessage()));
    }

    return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);

The field that needs to validate:

@Past
@NotNull
private Date birthDate;

Request body:

{
   "birthDate":""
}

Response:

[
    {
        "field": "birthDate",
        "message": "must not be null"
    },
    {
        "field": "birthDate",
        "message": "must not be null"
    }
]
0 Answers
Related