|
@@ -1,16 +1,24 @@
|
1
|
1
|
package io.zipcoder.tc_spring_poll_application.dtos.error;
|
2
|
2
|
import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
|
|
3
|
+import javafx.concurrent.Task;
|
|
4
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
5
|
+import org.springframework.context.MessageSource;
|
3
|
6
|
import org.springframework.http.HttpStatus;
|
4
|
7
|
import org.springframework.http.ResponseEntity;
|
|
8
|
+import org.springframework.validation.FieldError;
|
|
9
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
5
|
10
|
import org.springframework.web.bind.annotation.ControllerAdvice;
|
6
|
11
|
import org.springframework.web.bind.annotation.ExceptionHandler;
|
7
|
12
|
|
8
|
13
|
import javax.servlet.http.HttpServletRequest;
|
9
|
|
-import java.util.Date;
|
|
14
|
+import java.util.*;
|
10
|
15
|
|
11
|
16
|
@ControllerAdvice
|
12
|
17
|
public class RestExceptionHandler {
|
13
|
18
|
|
|
19
|
+ @Autowired
|
|
20
|
+ MessageSource messageSource;
|
|
21
|
+
|
14
|
22
|
@ExceptionHandler(ResourceNotFoundException.class)
|
15
|
23
|
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
|
16
|
24
|
ErrorDetail errorDetail = new ErrorDetail();
|
|
@@ -21,4 +29,29 @@ public class RestExceptionHandler {
|
21
|
29
|
|
22
|
30
|
return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
|
23
|
31
|
}
|
|
32
|
+
|
|
33
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
34
|
+ public ResponseEntity<?>
|
|
35
|
+ handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request){
|
|
36
|
+ ErrorDetail ed = new ErrorDetail();
|
|
37
|
+
|
|
38
|
+ ed.setTimeStamp(new Date().getTime());
|
|
39
|
+ ed.setTitle("Validation Failure");
|
|
40
|
+ ed.setStatus(404);
|
|
41
|
+ ed.setDetail("Unable to complete request.");
|
|
42
|
+ ed.setDeveloperMessage(Arrays.toString(manve.getStackTrace()));
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+ List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
|
|
46
|
+ for(FieldError fe : fieldErrors) {
|
|
47
|
+
|
|
48
|
+ List<ValidationError> validationErrorList = ed.getErrors().computeIfAbsent(fe.getField(), k -> new ArrayList<>());
|
|
49
|
+ ValidationError validationError = new ValidationError();
|
|
50
|
+ validationError.setCode(fe.getCode());
|
|
51
|
+ validationError.setMessage(messageSource.getMessage(fe,null));
|
|
52
|
+ validationErrorList.add(validationError);
|
|
53
|
+ }
|
|
54
|
+
|
|
55
|
+ return new ResponseEntity<>(ed, HttpStatus.BAD_REQUEST);
|
|
56
|
+ }
|
24
|
57
|
}
|