diff --git a/src/main/java/com/libraryman_api/exception/GlobalExceptionHandler.java b/src/main/java/com/libraryman_api/exception/GlobalExceptionHandler.java index 3ef1ca0..bcb7ec1 100644 --- a/src/main/java/com/libraryman_api/exception/GlobalExceptionHandler.java +++ b/src/main/java/com/libraryman_api/exception/GlobalExceptionHandler.java @@ -2,11 +2,15 @@ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.validation.FieldError; +import org.springframework.validation.ObjectError; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import java.util.Date; +import java.util.*; /** * Global exception handler for the LibraryMan API. This class provides @@ -69,4 +73,18 @@ public ResponseEntity invalidPasswordException(InvalidPasswordException ex, W ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> MethodArgumentNotValidException(MethodArgumentNotValidException ex){ + List allErrors = ex.getBindingResult().getAllErrors(); + HashMap map = new HashMap<>(); + allErrors.forEach(objectError -> { + String message=objectError.getDefaultMessage(); + String field=((FieldError) objectError).getField(); + map.put(field,message); + }); + + return new ResponseEntity<>(map,HttpStatus.BAD_REQUEST); + } + }