|
|
@@ -1,10 +1,15 @@
|
|
1
|
1
|
package io.zipcoder.tc_spring_poll_application.exception;
|
|
2
|
2
|
|
|
|
3
|
+import java.util.ArrayList;
|
|
3
|
4
|
import java.util.Date;
|
|
|
5
|
+import java.util.List;
|
|
4
|
6
|
import javax.servlet.http.HttpServletRequest;
|
|
5
|
7
|
import dtos.error.ErrorDetail;
|
|
|
8
|
+import dtos.error.ValidationError;
|
|
6
|
9
|
import org.springframework.http.HttpStatus;
|
|
7
|
10
|
import org.springframework.http.ResponseEntity;
|
|
|
11
|
+import org.springframework.validation.FieldError;
|
|
|
12
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
8
|
13
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
9
|
14
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
10
|
15
|
|
|
|
@@ -22,4 +27,32 @@ public class RestExceptionHandler {
|
|
22
|
27
|
return new ResponseEntity<>(errorDetail, null, HttpStatus.NOT_FOUND);
|
|
23
|
28
|
}
|
|
24
|
29
|
|
|
|
30
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
|
31
|
+ public ResponseEntity<?> handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
|
|
|
32
|
+ ErrorDetail errorDetail = new ErrorDetail();
|
|
|
33
|
+ // Populate errorDetail instance
|
|
|
34
|
+ errorDetail.setTimeStamp(new Date().getTime());
|
|
|
35
|
+ errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
|
|
|
36
|
+ String requestPath = (String) request.getAttribute("javax.servlet.error.request_uri");
|
|
|
37
|
+ if(requestPath == null) {
|
|
|
38
|
+ requestPath = request.getRequestURI();
|
|
|
39
|
+ }
|
|
|
40
|
+ errorDetail.setTitle("Validation Failed");
|
|
|
41
|
+ errorDetail.setDetail("Input validation failed");
|
|
|
42
|
+ errorDetail.setDeveloperMessage(manve.getClass().getName());
|
|
|
43
|
+ List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
|
|
|
44
|
+ for(FieldError fe : fieldErrors) {
|
|
|
45
|
+ List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
|
|
|
46
|
+ if(validationErrorList == null) {
|
|
|
47
|
+ validationErrorList = new ArrayList<>();
|
|
|
48
|
+ errorDetail.getErrors().put(fe.getField(), validationErrorList);
|
|
|
49
|
+ }
|
|
|
50
|
+ ValidationError validationError = new ValidationError();
|
|
|
51
|
+ validationError.setCode(fe.getCode());
|
|
|
52
|
+ validationError.setMessage(fe.getDefaultMessage());
|
|
|
53
|
+ validationErrorList.add(validationError);
|
|
|
54
|
+ }
|
|
|
55
|
+ return new ResponseEntity<>(errorDetail, null, HttpStatus. BAD_REQUEST);
|
|
|
56
|
+ }
|
|
|
57
|
+
|
|
25
|
58
|
}
|