Skip to content

Commit

Permalink
adding error handler. closes #9
Browse files Browse the repository at this point in the history
  • Loading branch information
springframeworkguru committed May 25, 2019
1 parent 8081fe2 commit 096dd29
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -23,14 +24,14 @@ public ResponseEntity<BeerDto> 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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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<List> validationErrorHandler(ConstraintViolationException ex){
List<String> errorsList = new ArrayList<>(ex.getConstraintViolations().size());

ex.getConstraintViolations().forEach(error -> errorsList.add(error.toString()));

return new ResponseEntity<>(errorsList, HttpStatus.BAD_REQUEST);
}

}

0 comments on commit 096dd29

Please sign in to comment.