Search code examples
javaspringspring-bootexceptionpath-variables

Why a validation message is not replaced in Spring Boot?


Now I developed REST API using Spring Boot.

I try to validate path parameter and handle a exception with custom message like this.

FooController.java

@Validated
@RestController
@RequiredArgsConstructor
public class FooController {

  private final BarService service;

  @GetMapping(value = "/test/{id}")
  public void invoke(@PathVariable @Digits(integer = 10, fraction = 0, message = "{message}") Long id) {
    service.get(id);
    ...
  }
}

ApiExceptionHandler.java

@RestControllerAdvice
@RequiredArgsConstructor
public class ApiExceptionHandler {

  @ExceptionHandler(ConstraintViolationException.class)
  public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException exception) {
    Map<String, String> messages = new HashMap<>();
    for (ConstraintViolation violation : exception.getConstraintViolations()) {
      messages.put("message", violation.getMessage());
    }
    return new ResponseEntity<>(messages, HttpStatus.BAD_REQUEST);
  }
}

ValidationMessages.properties

message={0} must not be more than {integer} digits

When I call this API by more than 10 digits (For example, [GET /test/12345678901]) to happen 400 error.

My expected response is

{
  message : id must not be more than 10 digits
}

But, actual response is

{
  message : {0} must not be more than 10 digits
}

So, my question is "Why a validation message is not replaced".

If this approach is wrong then is there any approach to come get expected response?

Thank you for reading my question.

Appendix Used Spring Boot version is 2.1.1


Solution

  • You must use ${validatedValue} to get the parameter in the message:

    message=${validatedValue} must not be more than {integer} digits
    

    Please find out more about message interpolation in the docs:

    https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.1#section-interpolation-with-message-expressions