From 34803f7aa00585e05ffbb38685ee9fef911ea3a5 Mon Sep 17 00:00:00 2001 From: Krzysztof Majewski Date: Tue, 26 Feb 2019 17:10:43 +0100 Subject: [PATCH] BAEL-2576 - add ControllerAdvice --- .../ConstraintViolationExceptionHandler.java | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java diff --git a/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java new file mode 100644 index 0000000000..645b36c2a5 --- /dev/null +++ b/spring-mvc-xml/src/main/java/com/baeldung/spring/controller/ConstraintViolationExceptionHandler.java @@ -0,0 +1,21 @@ +package com.baeldung.spring.controller; + +import org.springframework.http.HttpHeaders; +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 org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; + +import javax.validation.ConstraintViolationException; + +@ControllerAdvice +public class ConstraintViolationExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(value = {ConstraintViolationException.class}) + protected ResponseEntity handleConstraintViolation(ConstraintViolationException e, WebRequest request) { + return handleExceptionInternal(e, e.getMessage(), new HttpHeaders(), HttpStatus.BAD_REQUEST, request); + } +} +