Global Exception Handling
Relevant source files
The following files were used as context for generating this wiki page:
- Part1/API/src/main/java/com/example/api/exception/GlobalExceptionHandler.java
- Part1/API/src/main/java/com/example/api/controller/EmployeeController.java
- Part1/API/src/main/java/com/example/api/controller/DepartmentController.java
- Part1/API/src/main/java/com/example/api/service/EmployeeService.java
- Part1/API/src/main/java/com/example/api/service/DepartmentService.java
- Part1/API/src/main/resources/api-spec.yaml
The Global Exception Handling system in the SafeDispatch HQ Administration API provides a centralized mechanism for intercepting and processing errors across all REST controllers. By using a unified advice component, the application ensures that internal logic failures, validation errors, and missing resources are translated into consistent, client-friendly JSON responses rather than exposing raw stack traces.
This system simplifies error management by decoupling exception-throwing logic in the service and controller layers from the formatting logic required for HTTP responses. It specifically targets common web errors such as 404 Not Found, 400 Bad Request, and 500 Internal Server Error.
Sources: GlobalExceptionHandler.java:1-42, api-spec.yaml:104-108
Architecture and Components
The architecture relies on Spring's @ControllerAdvice to intercept exceptions thrown by any controller method. When an exception is raised, the GlobalExceptionHandler matches the exception type to a specific @ExceptionHandler method to generate a ResponseEntity.
Exception Handling Flow
The following diagram illustrates how an exception propagates from the business logic through the handler to the client.
The system ensures that even unexpected runtime errors are caught and sanitized before reaching the user.
Sources: GlobalExceptionHandler.java:12-42
Specific Exception Handlers
The system categorizes exceptions into four primary handlers to provide specific status codes and error messages.
1. Response Status Exceptions
Used frequently for resource lookups and business rule violations. For example, when an employee is not found by ID or is ineligible for promotion.
- Trigger:
ResponseStatusException - Response: Dynamic status code based on the exception (e.g., 404 for missing entities, 400 for business logic failures).
Sources: EmployeeController.java:33, EmployeeService.java:55
2. Validation Errors
Handles failures related to @Valid or @Validated bean constraints. It iterates through all field errors to provide a map of specific fields and their corresponding validation messages.
- Trigger:
MethodArgumentNotValidException - Response: 400 Bad Request with field-level details.
Sources: GlobalExceptionHandler.java:29-36
3. Argument Validation
Used for manual validation checks in controllers or services, such as verifying that a department budget is positive.
- Trigger:
IllegalArgumentException - Response: 400 Bad Request.
Sources: DepartmentController.java:32, DepartmentService.java:26
4. Catch-all Handler
A safety net for any unhandled Exception to prevent the leakage of internal implementation details.
- Trigger:
Exception.class - Response: 500 Internal Server Error with a generic prefix.
Sources: GlobalExceptionHandler.java:39-42
Summary of Error Responses
The API standardizes error outputs using the ErrorResponse schema defined in the API specification.
| Exception Source | HTTP Status | Description | Example Message |
|---|---|---|---|
ResponseStatusException | Variable (404/400) | Thrown when resources are missing or business logic fails. | "Employee not found" |
IllegalArgumentException | 400 Bad Request | Thrown for invalid input parameters or domain constraints. | "Budget must be positive" |
MethodArgumentNotValid | 400 Bad Request | Triggered by JSR-303 validation failures (e.g., @Email). | {"email": "must be a well-formed email address"} |
Exception (Generic) | 500 Internal Error | Catch-all for unexpected runtime failures. | "An unexpected error occurred: [message]" |
Sources: api-spec.yaml:104-108, GlobalExceptionHandler.java:12-42
Implementation Examples
Manual Business Logic Exception
In the EmployeeController, a promotion check throws a ResponseStatusException if eligibility criteria (e.g., 6 months tenure) are not met.
if (employee.getStartDate() == null || Period.between(employee.getStartDate(), LocalDate.now()).getMonths() < 6) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Employee not eligible for promotion");
}
Sources: EmployeeController.java:70-72
Domain Constraint Exception
The DepartmentService validates that a budget is positive before persisting a new department record.
public Department createDepartment(Department department) {
if (department.getBudget() == null || department.getBudget() <= 0) {
throw new IllegalArgumentException("Budget must be positive");
}
return departmentRepository.save(department);
}
Sources: DepartmentService.java:25-28
Conclusion
The Global Exception Handling module is a critical component for maintaining API reliability and security. By standardizing error responses through GlobalExceptionHandler.java, the system provides clear feedback to administrators using the HQ API while protecting sensitive system information from being exposed through stack traces.