|
8 | 8 | import org.springframework.http.ResponseEntity; |
9 | 9 | import org.springframework.security.authentication.BadCredentialsException; |
10 | 10 | import org.springframework.security.core.userdetails.UsernameNotFoundException; |
| 11 | +import org.springframework.validation.FieldError; |
| 12 | +import org.springframework.web.bind.MethodArgumentNotValidException; |
11 | 13 | import org.springframework.web.bind.annotation.ExceptionHandler; |
12 | 14 | import org.springframework.web.bind.annotation.RestControllerAdvice; |
13 | 15 | import org.springframework.web.context.request.WebRequest; |
14 | 16 |
|
15 | 17 | import java.time.LocalDateTime; |
16 | 18 | import java.util.HashMap; |
| 19 | +import java.util.List; |
17 | 20 | import java.util.Map; |
18 | 21 | import java.util.UUID; |
| 22 | +import java.util.stream.Collectors; |
19 | 23 |
|
20 | 24 | @RestControllerAdvice |
21 | 25 | public class GlobalExceptionHandler { |
@@ -101,6 +105,31 @@ public ResponseEntity<Map<String, Object>> handleSecurityException(SecurityExcep |
101 | 105 | return new ResponseEntity<>(response, HttpStatus.FORBIDDEN); |
102 | 106 | } |
103 | 107 |
|
| 108 | + /** |
| 109 | + * Handle Bean Validation errors (e.g. @Valid on request bodies) |
| 110 | + */ |
| 111 | + @ExceptionHandler(MethodArgumentNotValidException.class) |
| 112 | + public ResponseEntity<Map<String, Object>> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, WebRequest request) { |
| 113 | + String errorId = UUID.randomUUID().toString(); |
| 114 | + |
| 115 | + List<String> fieldMessages = ex.getBindingResult().getFieldErrors().stream() |
| 116 | + .map(FieldError::getDefaultMessage) |
| 117 | + .collect(Collectors.toList()); |
| 118 | + |
| 119 | + String combinedMessage = String.join("; ", fieldMessages); |
| 120 | + |
| 121 | + logger.warn("Validation error [" + errorId + "]: " + combinedMessage); |
| 122 | + |
| 123 | + Map<String, Object> response = createErrorResponse( |
| 124 | + "VALIDATION_ERROR", |
| 125 | + combinedMessage, |
| 126 | + HttpStatus.BAD_REQUEST, |
| 127 | + errorId |
| 128 | + ); |
| 129 | + |
| 130 | + return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); |
| 131 | + } |
| 132 | + |
104 | 133 | /** |
105 | 134 | * Handle illegal argument exceptions (validation errors) |
106 | 135 | */ |
|
0 commit comments