Class GlobalExceptionHandler
java.lang.Object
com.minicrm.mini_crm_api.exceptions.GlobalExceptionHandler
A global exception handler to catch and process exceptions across the entire
application.
This keeps the controller code clean and separates error handling logic.
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionorg.springframework.http.ResponseEntity<String>Handles exceptions thrown when business logic rules are violated, such as trying to create a customer with an email that already exists.org.springframework.http.ResponseEntity<String>Handles any other unexpected runtime exceptions.handleValidationExceptions(org.springframework.web.bind.MethodArgumentNotValidException ex) Handles exceptions thrown by the @Valid annotation when request body validation fails.
-
Constructor Details
-
GlobalExceptionHandler
public GlobalExceptionHandler()
-
-
Method Details
-
handleValidationExceptions
@ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class) public org.springframework.http.ResponseEntity<Map<String,String>> handleValidationExceptions(org.springframework.web.bind.MethodArgumentNotValidException ex) Handles exceptions thrown by the @Valid annotation when request body validation fails. This method extracts all the validation error messages and returns them in a structured map.- Parameters:
ex- The MethodArgumentNotValidException that was thrown.- Returns:
- A ResponseEntity with a 400 Bad Request status and a map of field errors.
-
handleBusinessException
@ExceptionHandler({java.lang.IllegalStateException.class,java.lang.IllegalArgumentException.class}) public org.springframework.http.ResponseEntity<String> handleBusinessException(RuntimeException ex) Handles exceptions thrown when business logic rules are violated, such as trying to create a customer with an email that already exists.- Parameters:
ex- The exception that was thrown.- Returns:
- A ResponseEntity with a 400 Bad Request status and the error message.
-
handleGenericException
@ExceptionHandler(java.lang.Exception.class) public org.springframework.http.ResponseEntity<String> handleGenericException(Exception ex) Handles any other unexpected runtime exceptions. This acts as a general safety net and prevents stack traces from being sent to the client.- Parameters:
ex- The generic Exception that was thrown.- Returns:
- A ResponseEntity with a 500 Internal Server Error status and a generic message.
-