-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathGlobalValidationExceptionHandler.java
More file actions
50 lines (41 loc) · 1.74 KB
/
Copy pathGlobalValidationExceptionHandler.java
File metadata and controls
50 lines (41 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.digitalsanctuary.spring.user.exception;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import lombok.extern.slf4j.Slf4j;
/**
* Global exception handler for validation errors across all API endpoints.
* Handles {@link MethodArgumentNotValidException} thrown by {@code @Valid} annotations
* and returns structured error responses with field-level validation details.
*/
@Slf4j
@ControllerAdvice
public class GlobalValidationExceptionHandler {
/**
* Handles validation errors from @Valid annotations on request bodies.
*
* @param ex the MethodArgumentNotValidException
* @return a ResponseEntity containing validation error details
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
log.warn("Validation error occurred: {}", ex.getMessage());
Map<String, Object> response = new HashMap<>();
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getAllErrors().forEach((error) -> {
String fieldName = ((FieldError) error).getField();
String errorMessage = error.getDefaultMessage();
errors.put(fieldName, errorMessage);
});
response.put("success", false);
response.put("code", 400);
response.put("message", "Validation failed");
response.put("errors", errors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
}