From e4b249c78421dd76c8388de11627d92573ab757c Mon Sep 17 00:00:00 2001 From: Amit Pandey Date: Mon, 4 Mar 2024 23:36:14 +0530 Subject: [PATCH] JAVA-30670 Improvement on Spring Validation article (#16023) --- .../controller/UserAccountController.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/spring/servicevalidation/controller/UserAccountController.java b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/spring/servicevalidation/controller/UserAccountController.java index 33d9966e42..5abe1609a3 100644 --- a/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/spring/servicevalidation/controller/UserAccountController.java +++ b/spring-boot-modules/spring-boot-validation/src/main/java/com/baeldung/spring/servicevalidation/controller/UserAccountController.java @@ -1,6 +1,9 @@ package com.baeldung.spring.servicevalidation.controller; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @@ -15,8 +18,12 @@ public class UserAccountController { private UserAccountService service; @PostMapping("/addUserAccount") - public Object addUserAccount(@RequestBody UserAccount userAccount) { - return service.addUserAccount(userAccount); + public ResponseEntity addUserAccount(@RequestBody UserAccount userAccount) { + try { + return ResponseEntity.ok(service.addUserAccount(userAccount)); + } catch(ConstraintViolationException e) { + return ResponseEntity.badRequest().body(e.getMessage()); + } } }