Global exception handling provides a centralized way to manage exceptions across your entire Spring Boot application.
@ControllerAdvice: Annotation for global exception handling@ExceptionHandler: Method-level annotation for specific exceptionsResponseEntity: For custom HTTP responses
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFound(
ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
"NOT_FOUND",
ex.getMessage(),
HttpStatus.NOT_FOUND.value());
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
}public class ErrorResponse {
private String code;
private String message;
private int status;
// Constructor, getters and setters
}@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationErrors(
MethodArgumentNotValidException ex) {
// Handle validation errors
}
@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<ErrorResponse> handleAccessDenied(
AccessDeniedException ex) {
// Handle access denied
}@ExceptionHandler({Exception.class, RuntimeException.class})
public ResponseEntity<ErrorResponse> handleGenericExceptions(
Exception ex) {
// Handle generic exceptions
}-
Organize by Exception Type:
- Create separate
@ControllerAdviceclasses for different exception categories
- Create separate
-
Standardize Responses:
- Use consistent error response structures
-
Log Exceptions:
- Always log exceptions before handling
-
Handle Spring Specific Exceptions:
MethodArgumentNotValidExceptionHttpRequestMethodNotSupportedExceptionHttpMediaTypeNotSupportedException
-
Security Considerations:
- Don't expose sensitive information in error responses
public class BusinessException extends RuntimeException {
private String errorCode;
public BusinessException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
// Getters
}
// Usage:
throw new BusinessException("Invalid order status", "ORD-001");- Use
@ResponseStatusannotation for default HTTP status
- Special handling for
@Validfailures
- Support for localized error messages
- Standardized error code system
- Standardized error response format