|
@@ -1,5 +1,6 @@
|
|
|
package es.uv.garcosda.controllers;
|
|
|
|
|
|
+import java.util.ArrayList;
|
|
|
import java.util.List;
|
|
|
|
|
|
import org.slf4j.Logger;
|
|
@@ -7,7 +8,10 @@ import org.slf4j.LoggerFactory;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.http.HttpStatus;
|
|
|
import org.springframework.http.ResponseEntity;
|
|
|
+import org.springframework.validation.FieldError;
|
|
|
+import org.springframework.web.bind.MethodArgumentNotValidException;
|
|
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
|
|
+import org.springframework.web.bind.annotation.ExceptionHandler;
|
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
|
import org.springframework.web.bind.annotation.PathVariable;
|
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
@@ -19,6 +23,9 @@ import org.springframework.web.bind.annotation.RestController;
|
|
|
import es.uv.garcosda.domain.Post;
|
|
|
import es.uv.garcosda.domain.PostDTO;
|
|
|
import es.uv.garcosda.services.PostService;
|
|
|
+import jakarta.validation.ConstraintViolation;
|
|
|
+import jakarta.validation.ConstraintViolationException;
|
|
|
+import jakarta.validation.Valid;
|
|
|
|
|
|
|
|
|
@RestController
|
|
@@ -46,7 +53,7 @@ public class BlogController {
|
|
|
}
|
|
|
|
|
|
@PostMapping("posts")
|
|
|
- public ResponseEntity<Post> create(@RequestBody PostDTO dto){
|
|
|
+ public ResponseEntity<Post> create(@Valid @RequestBody PostDTO dto){
|
|
|
Post p = ps.add(dto);
|
|
|
if(p.getId() != null) {
|
|
|
return new ResponseEntity<Post>(p, HttpStatus.OK);
|
|
@@ -87,4 +94,23 @@ public class BlogController {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ @ExceptionHandler(ConstraintViolationException.class)
|
|
|
+ public ResponseEntity<List<String>> validationError(ConstraintViolationException ex) {
|
|
|
+ List<String> msgs = new ArrayList<String>();
|
|
|
+ for(ConstraintViolation<?> v : ex.getConstraintViolations()) {
|
|
|
+ msgs.add(v.getPropertyPath().toString() + ": " + v.getMessage());
|
|
|
+ }
|
|
|
+ return new ResponseEntity<List<String>>(msgs, HttpStatus.BAD_REQUEST);
|
|
|
+ }
|
|
|
+
|
|
|
+ @ExceptionHandler(MethodArgumentNotValidException.class)
|
|
|
+ public ResponseEntity<List<String>> validationError(MethodArgumentNotValidException ex) {
|
|
|
+ List<String> msgs = new ArrayList<String>();
|
|
|
+ List<FieldError> errors = ex.getFieldErrors();
|
|
|
+ for(FieldError e : errors) {
|
|
|
+ msgs.add(e.getField() + ": " + e.getDefaultMessage());
|
|
|
+ }
|
|
|
+ return new ResponseEntity<List<String>>(msgs, HttpStatus.BAD_REQUEST);
|
|
|
+ }
|
|
|
+
|
|
|
}
|