ソースを参照

Fixed ValidationError

Kthomas 8 年 前
コミット
eac1d082a8

+ 1
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/Domain/Poll.java ファイルの表示

@@ -23,6 +23,7 @@ public class Poll {
23 23
     @OneToMany (cascade = CascadeType.ALL)
24 24
     @JoinColumn (name = "POLL_ID")
25 25
     @OrderBy
26
+    @Size(min = 2, max = 6)
26 27
     private Set<Option> options;
27 28
 
28 29
     public long getId() {

+ 4
- 7
src/main/java/io/zipcoder/tc_spring_poll_application/controller/PollController.java ファイルの表示

@@ -1,8 +1,8 @@
1 1
 package io.zipcoder.tc_spring_poll_application.controller;
2 2
 
3 3
 import io.zipcoder.tc_spring_poll_application.Domain.Poll;
4
+import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
4 5
 import io.zipcoder.tc_spring_poll_application.repositories.PollRepository;
5
-import org.springframework.boot.context.config.ResourceNotFoundException;
6 6
 import org.springframework.http.HttpHeaders;
7 7
 import org.springframework.http.HttpStatus;
8 8
 import org.springframework.http.ResponseEntity;
@@ -61,15 +61,12 @@ public class PollController {
61 61
     public ResponseEntity<?> getPoll(@PathVariable Long pollId) {
62 62
         verifyPoll(pollId);
63 63
         Poll p = pollRepository.findOne(pollId);
64
-        if (p == null) {
65
-            throw new ResourceNotFoundException("Poll with id: " + pollId + "does not exist");
66
-        }
67 64
         return new ResponseEntity<>(p, HttpStatus.OK);
68 65
     }
69 66
 
70
-    private void verifyPoll(Long pollId) throws ResourceNotFoundException{
71
-        Poll poll = pollRepository.findOne(pollId);
72
-        if(poll == null){
67
+    private void verifyPoll(Long pollId) {
68
+        Poll p = pollRepository.findOne(pollId);
69
+        if(p == null){
73 70
             throw new ResourceNotFoundException("Poll with id " + pollId + " does not exist");
74 71
         }
75 72
     }

+ 2
- 3
src/main/java/io/zipcoder/tc_spring_poll_application/controller/VoteController.java ファイルの表示

@@ -22,9 +22,8 @@ public class VoteController {
22 22
         vote = voteRepository.save(vote);
23 23
         // Set the headers for the newly created resource
24 24
         HttpHeaders responseHeaders = new HttpHeaders();
25
-        responseHeaders.setLocation(ServletUriComponentsBuilder.
26
-                fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
27
-        return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
25
+        responseHeaders.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(vote.getId()).toUri());
26
+        return new ResponseEntity<>(responseHeaders, HttpStatus.CREATED);
28 27
     }
29 28
 
30 29
     @RequestMapping(value="/polls/{pollId}/votes", method=RequestMethod.GET)

+ 58
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dto/error/ErrorDetail.java ファイルの表示

@@ -0,0 +1,58 @@
1
+package io.zipcoder.tc_spring_poll_application.dto.error;
2
+
3
+import java.util.HashMap;
4
+import java.util.List;
5
+import java.util.Map;
6
+
7
+public class ErrorDetail {
8
+    private String title;
9
+    private int status;
10
+    private String detail;
11
+    private long timeStamp;
12
+    private String developerMessage;
13
+    private Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
14
+
15
+    public String getTitle() {
16
+        return title;
17
+    }
18
+
19
+    public void setTitle(String title) {
20
+        this.title = title;
21
+    }
22
+
23
+    public int getStatus() {
24
+        return status;
25
+    }
26
+
27
+    public void setStatus(int status) {
28
+        this.status = status;
29
+    }
30
+
31
+    public String getDetail() {
32
+        return detail;
33
+    }
34
+
35
+    public void setDetail(String detail) {
36
+        this.detail = detail;
37
+    }
38
+
39
+    public long getTimeStamp() {
40
+        return timeStamp;
41
+    }
42
+
43
+    public void setTimeStamp(long timeStamp) {
44
+        this.timeStamp = timeStamp;
45
+    }
46
+
47
+    public String getDeveloperMessage() {
48
+        return developerMessage;
49
+    }
50
+
51
+    public void setDeveloperMessage(String developerMessage) {
52
+        this.developerMessage = developerMessage;
53
+    }
54
+
55
+    public Map<String, List<ValidationError>> getErrors() {
56
+        return this.errors;
57
+    }
58
+}

+ 63
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dto/error/RestExceptionHandler.java ファイルの表示

@@ -0,0 +1,63 @@
1
+package io.zipcoder.tc_spring_poll_application.dto.error;
2
+
3
+import io.zipcoder.tc_spring_poll_application.exception.ResourceNotFoundException;
4
+import org.springframework.context.MessageSource;
5
+import org.springframework.http.HttpStatus;
6
+import org.springframework.http.ResponseEntity;
7
+import org.springframework.validation.FieldError;
8
+import org.springframework.web.bind.MethodArgumentNotValidException;
9
+import org.springframework.web.bind.annotation.ControllerAdvice;
10
+import org.springframework.web.bind.annotation.ExceptionHandler;
11
+import javax.inject.Inject;
12
+import javax.servlet.http.HttpServletRequest;
13
+import java.util.ArrayList;
14
+import java.util.Date;
15
+import java.util.List;
16
+
17
+@ControllerAdvice
18
+public class RestExceptionHandler {
19
+
20
+    private final MessageSource messageSource;
21
+
22
+    @Inject
23
+    public RestExceptionHandler(MessageSource messageSource) {
24
+        this.messageSource = messageSource;
25
+    }
26
+
27
+    @ExceptionHandler(ResourceNotFoundException.class)
28
+    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException rnfe, HttpServletRequest request) {
29
+        ErrorDetail errorDetail = new ErrorDetail();
30
+        errorDetail.setTimeStamp(new Date().getTime());
31
+        errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
32
+        errorDetail.setTitle("Resource Not Found");
33
+        errorDetail.setDetail(rnfe.getMessage());
34
+        errorDetail.setDeveloperMessage(rnfe.getClass().getName());
35
+        return new ResponseEntity<>(errorDetail, HttpStatus.NOT_FOUND);
36
+    }
37
+
38
+    @ExceptionHandler(MethodArgumentNotValidException.class)
39
+    public ResponseEntity<?>
40
+    handleValidationError(MethodArgumentNotValidException manve,HttpServletRequest request){
41
+        ErrorDetail errorDetail = new ErrorDetail();
42
+        errorDetail.setTitle("Bad Request");
43
+        errorDetail.setDetail(manve.getMessage());
44
+        errorDetail.setDeveloperMessage(manve.getClass().getName());
45
+        errorDetail.setStatus(HttpStatus.BAD_REQUEST.value());
46
+        errorDetail.setTimeStamp(new Date().getTime());
47
+
48
+        List<FieldError> fieldErrors =  manve.getBindingResult().getFieldErrors();
49
+        for(FieldError fe : fieldErrors) {
50
+
51
+            List<ValidationError> validationErrorList = errorDetail.getErrors().get(fe.getField());
52
+            if(validationErrorList == null) {
53
+                validationErrorList = new ArrayList<>();
54
+                errorDetail.getErrors().put(fe.getField(), validationErrorList);
55
+            }
56
+            ValidationError validationError = new ValidationError();
57
+            validationError.setCode(fe.getCode());
58
+            validationError.setMessage(messageSource.getMessage(fe, null));
59
+            validationErrorList.add(validationError);
60
+        }
61
+        return new ResponseEntity<>(errorDetail, null, HttpStatus.BAD_REQUEST);
62
+    }
63
+}

+ 22
- 0
src/main/java/io/zipcoder/tc_spring_poll_application/dto/error/ValidationError.java ファイルの表示

@@ -0,0 +1,22 @@
1
+package io.zipcoder.tc_spring_poll_application.dto.error;
2
+
3
+public class ValidationError {
4
+    private String code;
5
+    private String message;
6
+
7
+    public String getCode() {
8
+        return code;
9
+    }
10
+
11
+    public void setCode(String code) {
12
+        this.code = code;
13
+    }
14
+
15
+    public String getMessage() {
16
+        return message;
17
+    }
18
+
19
+    public void setMessage(String message) {
20
+        this.message = message;
21
+    }
22
+}