Skip to content

Commit 0f606a4

Browse files
committed
fix (error handling): for validation errors with input fields
1 parent a4d2b91 commit 0f606a4

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

src/main/java/com/danielagapov/spawn/shared/exceptions/GlobalExceptionHandler.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,18 @@
88
import org.springframework.http.ResponseEntity;
99
import org.springframework.security.authentication.BadCredentialsException;
1010
import org.springframework.security.core.userdetails.UsernameNotFoundException;
11+
import org.springframework.validation.FieldError;
12+
import org.springframework.web.bind.MethodArgumentNotValidException;
1113
import org.springframework.web.bind.annotation.ExceptionHandler;
1214
import org.springframework.web.bind.annotation.RestControllerAdvice;
1315
import org.springframework.web.context.request.WebRequest;
1416

1517
import java.time.LocalDateTime;
1618
import java.util.HashMap;
19+
import java.util.List;
1720
import java.util.Map;
1821
import java.util.UUID;
22+
import java.util.stream.Collectors;
1923

2024
@RestControllerAdvice
2125
public class GlobalExceptionHandler {
@@ -101,6 +105,31 @@ public ResponseEntity<Map<String, Object>> handleSecurityException(SecurityExcep
101105
return new ResponseEntity<>(response, HttpStatus.FORBIDDEN);
102106
}
103107

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+
104133
/**
105134
* Handle illegal argument exceptions (validation errors)
106135
*/

0 commit comments

Comments
 (0)