diff --git a/src/main/java/guru/springframework/msscbeerservice/web/controller/BeerController.java b/src/main/java/guru/springframework/msscbeerservice/web/controller/BeerController.java index c6505467..c90379c0 100644 --- a/src/main/java/guru/springframework/msscbeerservice/web/controller/BeerController.java +++ b/src/main/java/guru/springframework/msscbeerservice/web/controller/BeerController.java @@ -3,6 +3,7 @@ import guru.springframework.msscbeerservice.web.model.BeerDto; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.util.UUID; @@ -23,14 +24,14 @@ public ResponseEntity getBeerById(@PathVariable("beerId") UUID beerId){ } @PostMapping - public ResponseEntity saveNewBeer(@RequestBody BeerDto beerDto){ + public ResponseEntity saveNewBeer(@RequestBody @Validated BeerDto beerDto){ //todo impl return new ResponseEntity(HttpStatus.CREATED); } @PutMapping("/{beerId}") - public ResponseEntity updateBeerById(@PathVariable("beerId") UUID beerId, @RequestBody BeerDto beerDto){ + public ResponseEntity updateBeerById(@PathVariable("beerId") UUID beerId, @RequestBody @Validated BeerDto beerDto){ //todo impl return new ResponseEntity(HttpStatus.NO_CONTENT); diff --git a/src/main/java/guru/springframework/msscbeerservice/web/controller/MvcExceptionHandler.java b/src/main/java/guru/springframework/msscbeerservice/web/controller/MvcExceptionHandler.java new file mode 100644 index 00000000..4ee897c2 --- /dev/null +++ b/src/main/java/guru/springframework/msscbeerservice/web/controller/MvcExceptionHandler.java @@ -0,0 +1,27 @@ +package guru.springframework.msscbeerservice.web.controller; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import javax.validation.ConstraintViolationException; +import java.util.ArrayList; +import java.util.List; + +/** + * Created by jt on 2019-05-25. + */ +@ControllerAdvice +public class MvcExceptionHandler { + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity validationErrorHandler(ConstraintViolationException ex){ + List errorsList = new ArrayList<>(ex.getConstraintViolations().size()); + + ex.getConstraintViolations().forEach(error -> errorsList.add(error.toString())); + + return new ResponseEntity<>(errorsList, HttpStatus.BAD_REQUEST); + } + +}