|
|
@@ -2,14 +2,24 @@ package io.zipcoder.tc_spring_poll_application.exception;
|
|
2
|
2
|
|
|
3
|
3
|
import org.springframework.http.HttpStatus;
|
|
4
|
4
|
import org.springframework.http.ResponseEntity;
|
|
|
5
|
+import org.springframework.validation.FieldError;
|
|
|
6
|
+import org.springframework.context.MessageSource;
|
|
|
7
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
5
|
8
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
6
|
9
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
10
|
+import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
|
7
|
11
|
|
|
|
12
|
+import javax.inject.Inject;
|
|
8
|
13
|
import javax.servlet.http.HttpServletRequest;
|
|
|
14
|
+import java.util.ArrayList;
|
|
9
|
15
|
import java.util.Date;
|
|
|
16
|
+import java.util.List;
|
|
10
|
17
|
|
|
11
|
18
|
@ControllerAdvice
|
|
12
|
|
-public class RestExceptionHandler {
|
|
|
19
|
+public class RestExceptionHandler extends ResponseEntityExceptionHandler {
|
|
|
20
|
+
|
|
|
21
|
+ @Inject
|
|
|
22
|
+ private MessageSource messageSource;
|
|
13
|
23
|
|
|
14
|
24
|
@ExceptionHandler(ResourceNotFoundException.class)
|
|
15
|
25
|
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
|
|
|
@@ -21,4 +31,23 @@ public class RestExceptionHandler {
|
|
21
|
31
|
return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
|
|
22
|
32
|
}
|
|
23
|
33
|
|
|
|
34
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
|
35
|
+ public ResponseEntity<?> handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
|
|
|
36
|
+ ErrorDetail errorDetail = new ErrorDetail();
|
|
|
37
|
+ List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
|
|
|
38
|
+ for (FieldError fe : fieldErrors) {
|
|
|
39
|
+
|
|
|
40
|
+ List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
|
|
|
41
|
+ if (validationErrorList == null) {
|
|
|
42
|
+ validationErrorList = new ArrayList<>();
|
|
|
43
|
+ errorDetail.getErrors().put(fe.getField(), validationErrorList);
|
|
|
44
|
+ }
|
|
|
45
|
+ ValidationError validationError = new ValidationError();
|
|
|
46
|
+ validationError.setCode(fe.getCode());
|
|
|
47
|
+ validationError.setMessage(messageSource.getMessage(fe, null));
|
|
|
48
|
+ validationErrorList.add(validationError);
|
|
|
49
|
+ }
|
|
|
50
|
+ return new ResponseEntity(errorDetail, HttpStatus.BAD_REQUEST);
|
|
|
51
|
+ }
|
|
|
52
|
+
|
|
24
|
53
|
}
|