@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorDto> handleValidationExceptions(MethodArgumentNotValidException ex) {
log.error("Validation error", ex);
// Collect all validation errors into a single string
String errorMessage = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.joining(", "));
ErrorDto errorDto = ErrorDto.builder()
.status(HttpStatus.BAD_REQUEST.value())
.message("Validation failed: " + errorMessage)
.build();
return new ResponseEntity<>(errorDto, HttpStatus.BAD_REQUEST);
}
Summary
- Added error handling for
MethodArgumentNotValidException