The GlobalExceptionsHandler class handles exceptions globally across all controllers. This class extends ResponseEntityExceptionHandler and uses @RestControllerAdvice to manage exceptions.
@RestControllerAdvice: This annotation indicates that the class provides advice across the entire application.@ExceptionHandler: This annotation is used to handle specific exceptions and return custom error responses.
resourceNotFound(): Handles customResourceNotFoundexceptions.handleResponseStatusException(): HandlesResponseStatusExceptionand returns a404 Not Foundstatus.handleSQLException(): HandlesSQLExceptionandNullPointerExceptionand returns a500 Internal Server Errorstatus.handlerMethodArgumentTypeMismatchException(): HandlesMethodArgumentTypeMismatchExceptionand returns a400 Bad Requeststatus.handleExceptionclass(): Handles all other generic exceptions and returns a503 Service Unavailablestatus.
ResourceNotFound: A custom exception class annotated with@ResponseStatus(HttpStatus.NOT_FOUND). It is used when a requested resource is not found.
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFound extends RuntimeException {
public ResourceNotFound(String message) {
super(message);
}
}-
The error response is encapsulated in the ErrorDetails class, which includes:
-
Error Message (error): A description of the error. -
Status Code (code): The HTTP status code. -
Timestamp (timestamp): The date and time when the error occurred.
public class ErrorDetails {
private String error;
private int code;
private Date timestamp;
public ErrorDetails(String error, int code, Date timestamp) {
this.error = error;
this.code = code;
this.timestamp = timestamp;
}
// Getters and Setters...
}
- Clone the Repository
git clone https://github.com/juyel/exception-handling-demo.git
cd exception-handling-demo
- Build the Project
mvn clean install
- ```
- Run the Application
```bash
mvn spring-boot:runContributions are welcome! Please open an issue or submit a pull request if you have any improvements or bug fixes