package com.release11.klaus.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindException; 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; /** * Custom exception handler for {@link ConstraintViolationException} * @author Rafał Żukowicz */ @ControllerAdvice public class MvcExceptionHandler { /** * Provides handling for {@link ConstraintViolationException} * @param e exception argument * @return response with error list and status 400 bad request */ @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity validationErrorHandler(ConstraintViolationException e){ List errors = new ArrayList<>(e.getConstraintViolations().size()); e.getConstraintViolations().forEach(constraintViolation -> { errors.add(constraintViolation.getPropertyPath() + " : " + constraintViolation.getMessage()); }); return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } /** * Provides handling for {@link BindException} * @param ex exception argument * @return response with error list and status 400 bad request */ @ExceptionHandler(BindException.class) public ResponseEntity handleBindException(BindException ex){ return new ResponseEntity(ex.getAllErrors(), HttpStatus.BAD_REQUEST); } }