|
@@ -0,0 +1,58 @@
|
|
1
|
+package io.zipcoder.tc_spring_poll_application.error;
|
|
2
|
+
|
|
3
|
+import io.zipcoder.tc_spring_poll_application.excepection.ResourceNotFoundException;
|
|
4
|
+import javafx.concurrent.Task;
|
|
5
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
6
|
+import org.springframework.context.MessageSource;
|
|
7
|
+import org.springframework.http.HttpStatus;
|
|
8
|
+import org.springframework.http.ResponseEntity;
|
|
9
|
+import org.springframework.validation.FieldError;
|
|
10
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
11
|
+import org.springframework.web.bind.annotation.ControllerAdvice;
|
|
12
|
+import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
13
|
+
|
|
14
|
+import javax.servlet.http.HttpServletRequest;
|
|
15
|
+import java.util.ArrayList;
|
|
16
|
+import java.util.Date;
|
|
17
|
+import java.util.List;
|
|
18
|
+
|
|
19
|
+@ControllerAdvice
|
|
20
|
+public class RestExceptionHandler {
|
|
21
|
+
|
|
22
|
+ @Autowired
|
|
23
|
+ MessageSource messageSource;
|
|
24
|
+
|
|
25
|
+ @ExceptionHandler(ResourceNotFoundException.class)
|
|
26
|
+ public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request){
|
|
27
|
+ ErrorDetail errorDetail = new ErrorDetail();
|
|
28
|
+ errorDetail.setTimeStamp(new Date().getTime());
|
|
29
|
+ errorDetail.setDeveloperMessage(rnfe.getMessage());
|
|
30
|
+ errorDetail.setDetail(rnfe.getCause().getMessage());
|
|
31
|
+
|
|
32
|
+ return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
|
|
33
|
+ }
|
|
34
|
+
|
|
35
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
36
|
+ public ResponseEntity<?> handleValidationError( MethodArgumentNotValidException manve, HttpServletRequest request){
|
|
37
|
+ ErrorDetail errorDetail = new ErrorDetail();
|
|
38
|
+ errorDetail.setTimeStamp(new Date().getTime());
|
|
39
|
+ errorDetail.setDeveloperMessage(new ResourceNotFoundException().getMessage());
|
|
40
|
+
|
|
41
|
+ List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
|
|
42
|
+ for(FieldError fe : fieldErrors) {
|
|
43
|
+
|
|
44
|
+ List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
|
|
45
|
+ if(validationErrorList == null) {
|
|
46
|
+ validationErrorList = new ArrayList<>();
|
|
47
|
+ errorDetail.getErrors().put(fe.getField(), validationErrorList);
|
|
48
|
+ }
|
|
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<>(fieldErrors, HttpStatus.NOT_FOUND);
|
|
56
|
+ }
|
|
57
|
+
|
|
58
|
+}
|