Overview
The User Management System uses a centralized error handling approach with Spring’s@RestControllerAdvice to catch and format exceptions consistently across all endpoints.
GlobalExceptionHandler
All validation and application exceptions are handled by theGlobalExceptionHandler class.
Location: src/main/java/dev/juanJe/userManagementSystem/config/GlobalExceptionHandler.java
How It Works
Exception occurs
When a validation error or exception is thrown in any controller, Spring catches it.
Handler matches exception type
The
@ExceptionHandler annotation maps specific exception types to handler methods.Error Response Format
All errors follow a standard JSON structure defined byErrorResponseDTO.
Location: src/main/java/dev/juanJe/userManagementSystem/dto/ErrorResponseDTO.java
Structure
Example Response
The
timestamp field is automatically populated when the ErrorResponseDTO is created using the constructor with three parameters.Common Error Scenarios
Validation Errors (400 Bad Request)
Triggered when request body fails Jakarta Validation constraints.Missing Required Fields
Missing Required Fields
Scenario: Client sends incomplete user registration dataRequest:Response:HTTP Status:
400 BAD REQUESTInvalid Email Format
Invalid Email Format
Scenario: Client provides malformed email addressRequest:Response:HTTP Status:
400 BAD REQUESTUsername Too Short
Username Too Short
Scenario: Username doesn’t meet minimum length requirementRequest:Response:HTTP Status:
400 BAD REQUESTWeak Password
Weak Password
Scenario: Password doesn’t meet complexity requirementsRequest:Response:HTTP Status:
400 BAD REQUESTMultiple Validation Errors
When multiple fields fail validation, all errors are returned together:HTTP Status Codes
The API uses standard HTTP status codes:| Status Code | Meaning | When Used |
|---|---|---|
400 | Bad Request | Validation errors, malformed requests |
401 | Unauthorized | Missing or invalid authentication token |
403 | Forbidden | Valid token but insufficient permissions |
404 | Not Found | Resource doesn’t exist |
409 | Conflict | Duplicate username or email |
500 | Internal Server Error | Unexpected server errors |
Currently, the
GlobalExceptionHandler explicitly handles validation errors (400). Other status codes may be returned by Spring Security filters or custom exception handlers.Handling Errors in Client Applications
JavaScript/TypeScript Example
Java Client Example
Extending Error Handling
To handle additional exception types, add new@ExceptionHandler methods:
When adding custom exception handlers, place more specific handlers before generic ones to ensure proper exception matching.