In Spring Boot, global exception handling can be done using @ControllerAdvice and @ExceptionHandler annotations. This allows you to centralize exception handling for all controllers, ensuring consistency and reducing duplicate code in your application.
Steps to Handle Exceptions Globally:
1. Create a Global Exception Handler Class:
- Create a class annotated with
@ControllerAdvice. This class will contain methods to handle specific exceptions globally across your application.
2. Use @ExceptionHandler for Specific Exceptions:
- Inside the
@ControllerAdviceclass, use@ExceptionHandlerto specify which exception types each method should handle. This ensures that when the exception occurs, the corresponding method will be invoked to handle it.
3. Return Custom Error Response:
- Each exception handler method can return a custom error response (such as a custom JSON object or a specific HTTP status) using
ResponseEntity.
Example: Global Exception Handling in Spring Boot
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; // Custom exception classclass ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}
// Global exception handler class
@ControllerAdvice
public class GlobalExceptionHandler {
// Handle specific exception (e.g., ResourceNotFoundException)
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex, WebRequest request) {
String errorMessage = ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.NOT_FOUND);
}
// Handle global exceptions (e.g., all unhandled exceptions)
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleGlobalException(Exception ex, WebRequest request) {
String errorMessage = "An unexpected error occurred: " + ex.getMessage();
return new ResponseEntity<>(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Explanation:
- Custom Exception:
ResourceNotFoundExceptionis a custom exception that you can throw when a resource (like a user or product) is not found in the database.- Global Exception Handler:
- The
GlobalExceptionHandlerclass is annotated with@ControllerAdvice, which makes it applicable globally to all controllers in the application. - The
handleResourceNotFoundExceptionmethod handles exceptions of typeResourceNotFoundExceptionand returns aNOT_FOUNDHTTP status (404). - The
handleGlobalExceptionmethod catches all other exceptions and returns a genericINTERNAL_SERVER_ERROR(500) status.
Benefits of Global Exception Handling:
- Consistency: Ensures that all exceptions are handled uniformly.
- Reusability: Centralizes exception handling, avoiding repeated code in controllers.
- Customization: You can customize error messages and response formats (JSON/XML) for different exceptions.