1

When calling GET endpoint in my scenario you must inform two input parameters code and date, the first one is annotated with @Size(min = 2, max = 2) the second with @DateTimeFormat(iso = DateTimeFormat.ISO.DATE). Said that, if you pass code = 123 and date = 2000-01-AA, you must receive two error messages one regarding ConstraintViolationException and MethodArgumentTypeMismatchException respectively.

Here is my code:

@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler({MethodArgumentTypeMismatchException.class, ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorResponse handleArgumentTypeMismatch(RuntimeException ex) {
        ErrorResponse errorResponse = ErrorResponse.builder().status(HttpStatus.BAD_REQUEST.value())
                .message(INVALID_VALUES_MESSAGE).errorDetail(new ErrorDetail(ex.getMessage())).build();
        return errorResponse;
    }
}

Currently, I'm only receiving the last parameter error message, in this case date, and the Spring is ignoring the code, is there any way to receive both error messages for code and date?

Wagner8170
  • 15
  • 6
  • DateTimeFormat is not a validation annotation. It tells Spring how to turn the string it receives into a Date. And only if the string can successfully be parsed, then the bean containing this date can be created, and validated. There's no way to validate a bean if it can't even be created due to an incorrect date format. – JB Nizet Aug 13 '19 at 19:02
  • Got it, so a possible solution should be, remove the annotation @DateTimeFormat, and add a regex to validate the date format as mentioned [here](https://stackoverflow.com/a/2149692/4192045). This approach has a trade-off, where I will have to execute the parse afterward Spring validates the input parameters. So, in the end, I will not accomplish the idea of having both error messages together. – Wagner8170 Aug 14 '19 at 13:07

0 Answers0