Overview
The E-Commerce API implements a centralized exception handling mechanism using Spring’s@ControllerAdvice to provide consistent error responses across all endpoints. This ensures that clients receive predictable, well-formatted error messages for various failure scenarios.
Global Exception Handler
TheGlobalExceptionHandler class (located at src/main/java/com/example/demo/core/infrastructures/exceptionhandler/GlobalExceptionHandler.java:10) serves as the central exception handling mechanism for the entire API.
All exceptions are intercepted and transformed into appropriate HTTP responses with status codes and descriptive error messages.
Architecture
@ControllerAdvice annotation to apply exception handling globally across all controllers, ensuring consistent error responses throughout the API.
Domain Exceptions
InvalidPasswordException
TheInvalidPasswordException is thrown when password validation fails during user registration or password updates.
400 - Bad Request
Plain text error message describing the specific validation failure
When This Exception Occurs
This exception is raised in theContrasenaVO value object (src/main/java/com/example/demo/usuario/domain/vo/ContrasenaVO.java:8) when creating or updating a password that fails validation rules.
Password Validation Rules
Password Validation Rules
The password must satisfy ALL of the following criteria:
-
Not Empty: Password cannot be null or empty string
- Error:
"La contraseña no puede estar vacía"
- Error:
-
Minimum Length: Must be at least 8 characters
- Error:
"La contraseña debe tener al menos 8 caracteres"
- Error:
-
Maximum Length: Cannot exceed 64 characters
- Error:
"La contraseña no puede superar los 64 caracteres"
- Error:
-
Complexity: Must contain at least one letter (A-Z, a-z) AND one digit (0-9)
- Error:
"La contraseña debe contener al menos una letra y un número"
- Error:
Example Error Responses
Empty PasswordValue Object Validation
IllegalArgumentException
While not explicitly handled by theGlobalExceptionHandler, the API uses standard IllegalArgumentException for other value object validations, such as price validation in PrecioVO (src/main/java/com/example/demo/producto/domain/vo/PrecioVO.java:6).
Standard Spring exception handling will catch
IllegalArgumentException and return a 500 Internal Server Error by default. Consider adding an explicit handler for this exception type in production environments.Price Validation Rules
ThePrecioVO value object enforces:
-
Not Null: Price cannot be null
- Error:
"El precio no puede ser nulo"
- Error:
-
Non-Negative: Price must be greater than or equal to 0
- Error:
"El precio no puede ser negativo"
- Error:
Error Response Format
Current Implementation
The API currently returns error messages as plain text strings in the response body. Example:Best Practices for Production
Recommended JSON Error Format:Exception Handling Flow
- Request Reception: Client sends request to controller endpoint
- Value Object Creation: Domain value objects (ContrasenaVO, PrecioVO) perform validation in constructors
- Exception Raised: Validation failure throws domain exception
- Global Handler Intercepts:
@ControllerAdvicecatches the exception - HTTP Response Mapped: Exception is converted to appropriate HTTP status and message
- Client Receives Error: Consistent error format returned to client
HTTP Status Codes
The API uses the following HTTP status codes for error responses:Validation errors, invalid input data, or business rule violations
InvalidPasswordException- Password validation failuresIllegalArgumentException- Value object validation failures (e.g., invalid price)
Unhandled exceptions and unexpected errors
- Exceptions not explicitly caught by
GlobalExceptionHandler
Extending Exception Handling
To add custom exception handling:-
Create a Custom Exception Class
-
Add Handler Method to GlobalExceptionHandler
-
Throw Exception in Domain Logic
Related Endpoints
- User Registration - Can trigger
InvalidPasswordException - User Login - Can trigger
InvalidPasswordException
Security Considerations
Recommendations:- Log detailed error information server-side for debugging
- Return generic error messages to clients in production
- Implement rate limiting on endpoints that trigger validation errors to prevent abuse
- Never expose stack traces in API responses