Skip to content

Instantly share code, notes, and snippets.

@ddanielsantos
Created February 1, 2023 20:30
Show Gist options
  • Save ddanielsantos/bc7885d65ca4621e7315e58c22cbec27 to your computer and use it in GitHub Desktop.
Save ddanielsantos/bc7885d65ca4621e7315e58c22cbec27 to your computer and use it in GitHub Desktop.
@ControllerAdvice
class ValidationHandler extends ResponseEntityExceptionHandler {
@Override
@ResponseBody
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request
) {
HashMap<String, List<String>> body = new HashMap<>();
List<String> errors = ex
.getBindingResult()
.getFieldErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
body.put("errors", errors);
return handleExceptionInternal(ex, body, headers, HttpStatus.BAD_REQUEST, request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment