I'll provide a comprehensive solution for handling JpaSystemException in a Spring Boot application's global exception handler. I'll show you multiple approaches with best practices.
1. Basic Implementation
@ControllerAdvice
public class GlobalExceptionHandler {
private static final String GENERIC_DATABASE_ERROR_MESSAGE =
"An unexpected database error occurred. Please try again later.";
@ExceptionHandler(JpaSystemException.class)
public ResponseEntity<ErrorResponse> handleJpaSystemException(
JpaSystemException ex,
WebRequest request
) {
// Log the actual exception (important for debugging)
log.error("JPA System Exception occurred", ex);
ErrorResponse errorResponse = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
GENERIC_DATABASE_ERROR_MESSAGE
);
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Simple Error Response DTO
@Data
@AllArgsConstructor
public class ErrorResponse {
private int status;
private String message;
private LocalDateTime timestamp = LocalDateTime.now();
}
2. Enhanced Implementation with Logging
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
private static final String GENERIC_DATABASE_ERROR_MESSAGE =
"An unexpected database error occurred. Please try again later.";
@ExceptionHandler(JpaSystemException.class)
public ResponseEntity<ErrorResponse> handleJpaSystemException(
JpaSystemException ex,
WebRequest request
) {
// Detailed logging without exposing sensitive information
log.error("Database operation failed: {}",
ex.getMessage(),
ex
);
ErrorResponse errorResponse = ErrorResponse.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.message(GENERIC_DATABASE_ERROR_MESSAGE)
.errorCode("DATABASE_ERROR")
.build();
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Enhanced Error Response with Builder
@Data
@Builder
public class ErrorResponse {
private int status;
private String message;
private String errorCode;
private LocalDateTime timestamp = LocalDateTime.now();
}
3. Advanced Implementation with Correlation ID
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
private static final String GENERIC_DATABASE_ERROR_MESSAGE =
"An unexpected database error occurred. Please try again later.";
@ExceptionHandler(JpaSystemException.class)
public ResponseEntity<ErrorResponse> handleJpaSystemException(
JpaSystemException ex,
WebRequest request
) {
// Generate a unique correlation ID for tracing
String correlationId = UUID.randomUUID().toString();
// Log with correlation ID for easier tracking
log.error(
"Correlation ID: {} - Database operation failed",
correlationId,
ex
);
ErrorResponse errorResponse = ErrorResponse.builder()
.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
.message(GENERIC_DATABASE_ERROR_MESSAGE)
.errorCode("DATABASE_ERROR")
.correlationId(correlationId)
.build();
return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Error Response with Correlation ID
@Data
@Builder
public class ErrorResponse {
private int status;
private String message;
private String errorCode;
private String correlationId;
private LocalDateTime timestamp = LocalDateTime.now();
}
Best Practices Explained:
-
Generic Error Message:
- Use a non-descriptive message that doesn't reveal internal system details
- Prevents potential security risks
-
Logging:
- Always log the full exception for internal debugging
- Use
log.error() to capture stack trace
- Never log sensitive information
-
Error Response:
- Include a status code
- Provide a user-friendly message
- Optional error code for client-side handling
- Timestamp for tracking
- (Optional) Correlation ID for tracing
Additional Recommendations:
- Internationalization: Consider using message source for error messages
- Security: Ensure no sensitive information is leaked
- Monitoring: Use correlation IDs for better traceability
Potential Enhancements:
// If you want more dynamic error handling
@Component
public class ErrorMessageResolver {
public String resolveMessage(Exception ex) {
// Potential logic to dynamically generate messages
return GENERIC_DATABASE_ERROR_MESSAGE;
}
}
When to Use:
- Use this approach when you want to:
- Hide internal system complexities
- Provide a consistent error response
- Maintain system security
- Enable easier debugging
Potential Customization:
// If you need more specific handling based on exception subtypes
@ExceptionHandler({
JpaSystemException.class,
DataIntegrityViolationException.class
})
public ResponseEntity<ErrorResponse> handleDatabaseExceptions(Exception ex) {
// Potentially different handling for different database-related exceptions
}
Logging Configuration (application.properties)
# Recommended logging configuration
logging.level.org.springframework.orm.jpa=ERROR
logging.level.org.hibernate=ERROR
This comprehensive approach provides a robust, secure, and maintainable way to handle JpaSystemException in a Spring Boot application. The implementation ensures that internal system details are not exposed while providing meaningful feedback to the client and maintaining detailed logs for debugging purposes.