From 38178d9c33324ee1b49174ea230fec18675c0194 Mon Sep 17 00:00:00 2001 From: earlspilner Date: Sun, 11 Aug 2024 01:59:42 +0300 Subject: [PATCH] fix: update correct 404 responses handling --- .../advice/ExceptionControllerAdvice.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/springframework/samples/petclinic/rest/advice/ExceptionControllerAdvice.java b/src/main/java/org/springframework/samples/petclinic/rest/advice/ExceptionControllerAdvice.java index b1aa4600e..ef6f974c9 100644 --- a/src/main/java/org/springframework/samples/petclinic/rest/advice/ExceptionControllerAdvice.java +++ b/src/main/java/org/springframework/samples/petclinic/rest/advice/ExceptionControllerAdvice.java @@ -16,8 +16,6 @@ package org.springframework.samples.petclinic.rest.advice; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -62,7 +60,7 @@ public ErrorInfo(Exception ex) { /** * Handles all general exceptions by returning a 500 Internal Server Error status with error details. * - * @param e The exception to be handled + * @param e The exception to be handled * @return A {@link ResponseEntity} containing the error information and a 500 Internal Server Error status */ @ExceptionHandler(Exception.class) @@ -107,4 +105,23 @@ public ResponseEntity handleDataIntegrityViolationException(DataInteg return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorInfo); } + /** + * Handles exception thrown by Bean Validation on controller methods parameters + * + * @param ex The thrown exception + * @return an empty response entity + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + @ResponseStatus(BAD_REQUEST) + @ResponseBody + public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) { + BindingErrorsResponse errors = new BindingErrorsResponse(); + BindingResult bindingResult = ex.getBindingResult(); + if (bindingResult.hasErrors()) { + errors.addAllErrors(bindingResult); + return ResponseEntity.badRequest().body(new ErrorInfo("MethodArgumentNotValidException", "Validation failed")); + } + return ResponseEntity.badRequest().build(); + } + }