Skip to content

Instantly share code, notes, and snippets.

@mesmacosta
Last active August 8, 2018 19:11
Show Gist options
  • Save mesmacosta/976e78de08909b791473f3cb44768d95 to your computer and use it in GitHub Desktop.
Save mesmacosta/976e78de08909b791473f3cb44768d95 to your computer and use it in GitHub Desktop.
Method in controller:
@RequestMapping("/hi")
public String sayHi(@Size(max = 10, message = "name should at most 10 characters long") @RequestParam("name") String name) {
return "Hi " + name;
Controller Advice:
@ExceptionHandler(value = {ConstraintViolationException.class})
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public String handleValidationFailure(ConstraintViolationException ex) {
StringBuilder messages = new StringBuilder();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
messages.append(violation.getMessage() + "\n");
}
return messages.toString();
}
Config:
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment