Skip to main content

confluent_kafka/common/errors/
mod.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Kafka's exception classes.
16//!
17//! Translates `org.apache.kafka.common.errors`. Each Java exception class is one
18//! struct in its own file, named with the `Exception` -> `Error` substitution of
19//! CLAUDE.md §2, and declares its `extends` chain through its
20//! `ErrorHierarchy` impl rather
21//! than through a predicate that enumerates it from the outside.
22//!
23//! The error code for each class lives in its
24//! `ErrorCode` impl — Java keeps the
25//! same association in `Errors`' `CLASS_TO_ERROR` map — while the default
26//! message strings stay in `Errors`, exactly
27//! as Java stores them on the enum constant and passes them to the class's
28//! constructor.
29
30mod api_error;
31mod authentication_error;
32mod authorization_error;
33mod authorizer_not_ready_error;
34mod bootstrap_resolution_error;
35mod broker_id_not_registered_error;
36mod broker_not_available_error;
37mod cluster_authorization_error;
38mod concurrent_transactions_error;
39mod controller_id_not_registered_error;
40mod controller_moved_error;
41mod coordinator_load_in_progress_error;
42mod coordinator_not_available_error;
43mod corrupt_record_error;
44mod delegation_token_authorization_error;
45mod delegation_token_disabled_error;
46mod delegation_token_expired_error;
47mod delegation_token_not_found_error;
48mod delegation_token_owner_mismatch_error;
49mod disconnect_error;
50mod duplicate_broker_registration_error;
51mod duplicate_resource_error;
52mod duplicate_sequence_error;
53mod duplicate_voter_error;
54mod election_not_needed_error;
55mod eligible_leaders_not_available_error;
56mod feature_update_failed_error;
57mod fenced_instance_id_error;
58mod fenced_leader_epoch_error;
59mod fenced_member_epoch_error;
60mod fenced_state_epoch_error;
61mod fetch_session_id_not_found_error;
62mod fetch_session_topic_id_error;
63mod group_authorization_error;
64mod group_deletion_failed_error;
65mod group_id_not_found_error;
66mod group_max_size_reached_error;
67mod group_not_empty_error;
68mod group_subscribed_to_topic_error;
69mod illegal_generation_error;
70mod illegal_sasl_state_error;
71mod inconsistent_cluster_id_error;
72mod inconsistent_group_protocol_error;
73mod inconsistent_topic_id_error;
74mod inconsistent_voter_set_error;
75mod ineligible_replica_error;
76mod interrupt_error;
77mod invalid_commit_offset_size_error;
78mod invalid_configuration_error;
79mod invalid_fetch_session_epoch_error;
80mod invalid_fetch_size_error;
81mod invalid_group_id_error;
82mod invalid_offset_error;
83mod invalid_partitions_error;
84mod invalid_pid_mapping_error;
85mod invalid_principal_type_error;
86mod invalid_producer_epoch_error;
87mod invalid_record_state_error;
88mod invalid_registration_error;
89mod invalid_regular_expression;
90mod invalid_replica_assignment_error;
91mod invalid_replication_factor_error;
92mod invalid_request_error;
93mod invalid_required_acks_error;
94mod invalid_session_timeout_error;
95mod invalid_share_session_epoch_error;
96mod invalid_timestamp_error;
97mod invalid_topic_error;
98mod invalid_txn_state_error;
99mod invalid_txn_timeout_error;
100mod invalid_update_version_error;
101mod invalid_voter_key_error;
102mod kafka_storage_error;
103mod leader_not_available_error;
104mod listener_not_found_error;
105mod log_dir_not_found_error;
106mod member_id_required_error;
107mod mismatched_endpoint_type_error;
108mod network_error;
109mod new_leader_elected_error;
110mod no_reassignment_in_progress_error;
111mod not_controller_error;
112mod not_coordinator_error;
113mod not_enough_replicas_after_append_error;
114mod not_enough_replicas_error;
115mod not_leader_or_follower_error;
116mod offset_metadata_too_large;
117mod offset_moved_to_tiered_storage_error;
118mod offset_not_available_error;
119mod offset_out_of_range_error;
120mod operation_not_attempted_error;
121mod out_of_order_sequence_error;
122mod policy_violation_error;
123mod position_out_of_range_error;
124mod preferred_leader_not_available_error;
125mod principal_deserialization_error;
126mod producer_fenced_error;
127mod reassignment_in_progress_error;
128mod rebalance_in_progress_error;
129mod rebootstrap_required_error;
130mod record_batch_too_large_error;
131pub mod record_deserialization_error;
132mod record_too_large_error;
133mod replica_not_available_error;
134mod resource_not_found_error;
135mod sasl_authentication_error;
136mod security_disabled_error;
137mod serialization_error;
138mod share_session_limit_reached_error;
139mod share_session_not_found_error;
140mod snapshot_not_found_error;
141mod ssl_authentication_error;
142mod stale_broker_epoch_error;
143mod stale_member_epoch_error;
144mod streams_invalid_topology_epoch_error;
145mod streams_invalid_topology_error;
146mod streams_topology_description_update_failed_error;
147mod streams_topology_fenced_error;
148mod telemetry_too_large_error;
149mod throttling_quota_exceeded_error;
150mod timeout_error;
151mod topic_authorization_error;
152mod topic_deletion_disabled_error;
153mod topic_exists_error;
154mod transaction_abortable_error;
155mod transaction_aborted_error;
156mod transaction_coordinator_fenced_error;
157mod transactional_id_authorization_error;
158mod transactional_id_not_found_error;
159mod unacceptable_credential_error;
160mod unknown_controller_id_error;
161mod unknown_leader_epoch_error;
162mod unknown_member_id_error;
163mod unknown_producer_id_error;
164mod unknown_server_error;
165mod unknown_subscription_id_error;
166mod unknown_topic_id_error;
167mod unknown_topic_or_partition_error;
168mod unreleased_instance_id_error;
169mod unstable_offset_commit_error;
170mod unsupported_assignor_error;
171mod unsupported_by_authentication_error;
172mod unsupported_compression_type_error;
173mod unsupported_endpoint_type_error;
174mod unsupported_for_message_format_error;
175mod unsupported_sasl_mechanism_error;
176mod unsupported_version_error;
177mod voter_not_found_error;
178mod wakeup_error;
179
180/// Render a set of strings the way Java's `AbstractCollection.toString()` does —
181/// `[a, b]`, elements unquoted and comma-space separated — so the messages of
182/// [`TopicAuthorizationError`](topic_authorization_error::TopicAuthorizationError)
183/// and [`InvalidTopicError`](invalid_topic_error::InvalidTopicError) match Java's
184/// `getMessage()` format. Rust's `HashSet` `Debug` would instead print
185/// `{"a", "b"}`. Iteration order is unspecified, exactly as for a Java `HashSet`.
186fn format_java_set(set: &std::collections::HashSet<String>) -> String {
187    let mut out = String::from("[");
188    for (i, item) in set.iter().enumerate() {
189        if i > 0 {
190            out.push_str(", ");
191        }
192        out.push_str(item);
193    }
194    out.push(']');
195    out
196}
197
198pub use api_error::ApiError;
199pub use authentication_error::AuthenticationError;
200pub use authorization_error::AuthorizationError;
201pub use authorizer_not_ready_error::AuthorizerNotReadyError;
202pub use bootstrap_resolution_error::BootstrapResolutionError;
203pub use broker_id_not_registered_error::BrokerIdNotRegisteredError;
204pub use broker_not_available_error::BrokerNotAvailableError;
205pub use cluster_authorization_error::ClusterAuthorizationError;
206pub use concurrent_transactions_error::ConcurrentTransactionsError;
207pub use controller_id_not_registered_error::ControllerIdNotRegisteredError;
208pub use controller_moved_error::ControllerMovedError;
209pub use coordinator_load_in_progress_error::CoordinatorLoadInProgressError;
210pub use coordinator_not_available_error::CoordinatorNotAvailableError;
211pub use corrupt_record_error::CorruptRecordError;
212pub use delegation_token_authorization_error::DelegationTokenAuthorizationError;
213pub use delegation_token_disabled_error::DelegationTokenDisabledError;
214pub use delegation_token_expired_error::DelegationTokenExpiredError;
215pub use delegation_token_not_found_error::DelegationTokenNotFoundError;
216pub use delegation_token_owner_mismatch_error::DelegationTokenOwnerMismatchError;
217pub use disconnect_error::DisconnectError;
218pub use duplicate_broker_registration_error::DuplicateBrokerRegistrationError;
219pub use duplicate_resource_error::DuplicateResourceError;
220pub use duplicate_sequence_error::DuplicateSequenceError;
221pub use duplicate_voter_error::DuplicateVoterError;
222pub use election_not_needed_error::ElectionNotNeededError;
223pub use eligible_leaders_not_available_error::EligibleLeadersNotAvailableError;
224pub use feature_update_failed_error::FeatureUpdateFailedError;
225pub use fenced_instance_id_error::FencedInstanceIdError;
226pub use fenced_leader_epoch_error::FencedLeaderEpochError;
227pub use fenced_member_epoch_error::FencedMemberEpochError;
228pub use fenced_state_epoch_error::FencedStateEpochError;
229pub use fetch_session_id_not_found_error::FetchSessionIdNotFoundError;
230pub use fetch_session_topic_id_error::FetchSessionTopicIdError;
231pub use group_authorization_error::GroupAuthorizationError;
232pub use group_deletion_failed_error::GroupDeletionFailedError;
233pub use group_id_not_found_error::GroupIdNotFoundError;
234pub use group_max_size_reached_error::GroupMaxSizeReachedError;
235pub use group_not_empty_error::GroupNotEmptyError;
236pub use group_subscribed_to_topic_error::GroupSubscribedToTopicError;
237pub use illegal_generation_error::IllegalGenerationError;
238pub use illegal_sasl_state_error::IllegalSaslStateError;
239pub use inconsistent_cluster_id_error::InconsistentClusterIdError;
240pub use inconsistent_group_protocol_error::InconsistentGroupProtocolError;
241pub use inconsistent_topic_id_error::InconsistentTopicIdError;
242pub use inconsistent_voter_set_error::InconsistentVoterSetError;
243pub use ineligible_replica_error::IneligibleReplicaError;
244pub use interrupt_error::InterruptError;
245pub use invalid_commit_offset_size_error::InvalidCommitOffsetSizeError;
246pub use invalid_configuration_error::InvalidConfigurationError;
247pub use invalid_fetch_session_epoch_error::InvalidFetchSessionEpochError;
248pub use invalid_fetch_size_error::InvalidFetchSizeError;
249pub use invalid_group_id_error::InvalidGroupIdError;
250pub use invalid_offset_error::InvalidOffsetError;
251pub use invalid_partitions_error::InvalidPartitionsError;
252pub use invalid_pid_mapping_error::InvalidPidMappingError;
253pub use invalid_principal_type_error::InvalidPrincipalTypeError;
254pub use invalid_producer_epoch_error::InvalidProducerEpochError;
255pub use invalid_record_state_error::InvalidRecordStateError;
256pub use invalid_registration_error::InvalidRegistrationError;
257pub use invalid_regular_expression::InvalidRegularExpression;
258pub use invalid_replica_assignment_error::InvalidReplicaAssignmentError;
259pub use invalid_replication_factor_error::InvalidReplicationFactorError;
260pub use invalid_request_error::InvalidRequestError;
261pub use invalid_required_acks_error::InvalidRequiredAcksError;
262pub use invalid_session_timeout_error::InvalidSessionTimeoutError;
263pub use invalid_share_session_epoch_error::InvalidShareSessionEpochError;
264pub use invalid_timestamp_error::InvalidTimestampError;
265pub use invalid_topic_error::InvalidTopicError;
266pub use invalid_txn_state_error::InvalidTxnStateError;
267pub use invalid_txn_timeout_error::InvalidTxnTimeoutError;
268pub use invalid_update_version_error::InvalidUpdateVersionError;
269pub use invalid_voter_key_error::InvalidVoterKeyError;
270pub use kafka_storage_error::KafkaStorageError;
271pub use leader_not_available_error::LeaderNotAvailableError;
272pub use listener_not_found_error::ListenerNotFoundError;
273pub use log_dir_not_found_error::LogDirNotFoundError;
274pub use member_id_required_error::MemberIdRequiredError;
275pub use mismatched_endpoint_type_error::MismatchedEndpointTypeError;
276pub use network_error::NetworkError;
277pub use new_leader_elected_error::NewLeaderElectedError;
278pub use no_reassignment_in_progress_error::NoReassignmentInProgressError;
279pub use not_controller_error::NotControllerError;
280pub use not_coordinator_error::NotCoordinatorError;
281pub use not_enough_replicas_after_append_error::NotEnoughReplicasAfterAppendError;
282pub use not_enough_replicas_error::NotEnoughReplicasError;
283pub use not_leader_or_follower_error::NotLeaderOrFollowerError;
284pub use offset_metadata_too_large::OffsetMetadataTooLarge;
285pub use offset_moved_to_tiered_storage_error::OffsetMovedToTieredStorageError;
286pub use offset_not_available_error::OffsetNotAvailableError;
287pub use offset_out_of_range_error::OffsetOutOfRangeError;
288pub use operation_not_attempted_error::OperationNotAttemptedError;
289pub use out_of_order_sequence_error::OutOfOrderSequenceError;
290pub use policy_violation_error::PolicyViolationError;
291pub use position_out_of_range_error::PositionOutOfRangeError;
292pub use preferred_leader_not_available_error::PreferredLeaderNotAvailableError;
293pub use principal_deserialization_error::PrincipalDeserializationError;
294pub use producer_fenced_error::ProducerFencedError;
295pub use reassignment_in_progress_error::ReassignmentInProgressError;
296pub use rebalance_in_progress_error::RebalanceInProgressError;
297pub use rebootstrap_required_error::RebootstrapRequiredError;
298pub use record_batch_too_large_error::RecordBatchTooLargeError;
299pub use record_deserialization_error::{DeserializationErrorOrigin, RecordDeserializationError};
300pub use record_too_large_error::RecordTooLargeError;
301pub use replica_not_available_error::ReplicaNotAvailableError;
302pub use resource_not_found_error::ResourceNotFoundError;
303pub use sasl_authentication_error::SaslAuthenticationError;
304pub use security_disabled_error::SecurityDisabledError;
305pub use serialization_error::SerializationError;
306pub use share_session_limit_reached_error::ShareSessionLimitReachedError;
307pub use share_session_not_found_error::ShareSessionNotFoundError;
308pub use snapshot_not_found_error::SnapshotNotFoundError;
309pub use ssl_authentication_error::SslAuthenticationError;
310pub use stale_broker_epoch_error::StaleBrokerEpochError;
311pub use stale_member_epoch_error::StaleMemberEpochError;
312pub use streams_invalid_topology_epoch_error::StreamsInvalidTopologyEpochError;
313pub use streams_invalid_topology_error::StreamsInvalidTopologyError;
314pub use streams_topology_description_update_failed_error::StreamsTopologyDescriptionUpdateFailedError;
315pub use streams_topology_fenced_error::StreamsTopologyFencedError;
316pub use telemetry_too_large_error::TelemetryTooLargeError;
317pub use throttling_quota_exceeded_error::ThrottlingQuotaExceededError;
318pub use timeout_error::TimeoutError;
319pub use topic_authorization_error::TopicAuthorizationError;
320pub use topic_deletion_disabled_error::TopicDeletionDisabledError;
321pub use topic_exists_error::TopicExistsError;
322pub use transaction_abortable_error::TransactionAbortableError;
323pub use transaction_aborted_error::TransactionAbortedError;
324pub use transaction_coordinator_fenced_error::TransactionCoordinatorFencedError;
325pub use transactional_id_authorization_error::TransactionalIdAuthorizationError;
326pub use transactional_id_not_found_error::TransactionalIdNotFoundError;
327pub use unacceptable_credential_error::UnacceptableCredentialError;
328pub use unknown_controller_id_error::UnknownControllerIdError;
329pub use unknown_leader_epoch_error::UnknownLeaderEpochError;
330pub use unknown_member_id_error::UnknownMemberIdError;
331pub use unknown_producer_id_error::UnknownProducerIdError;
332pub use unknown_server_error::UnknownServerError;
333pub use unknown_subscription_id_error::UnknownSubscriptionIdError;
334pub use unknown_topic_id_error::UnknownTopicIdError;
335pub use unknown_topic_or_partition_error::UnknownTopicOrPartitionError;
336pub use unreleased_instance_id_error::UnreleasedInstanceIdError;
337pub use unstable_offset_commit_error::UnstableOffsetCommitError;
338pub use unsupported_assignor_error::UnsupportedAssignorError;
339pub use unsupported_by_authentication_error::UnsupportedByAuthenticationError;
340pub use unsupported_compression_type_error::UnsupportedCompressionTypeError;
341pub use unsupported_endpoint_type_error::UnsupportedEndpointTypeError;
342pub use unsupported_for_message_format_error::UnsupportedForMessageFormatError;
343pub use unsupported_sasl_mechanism_error::UnsupportedSaslMechanismError;
344pub use unsupported_version_error::UnsupportedVersionError;
345pub(crate) use unsupported_version_error::UnsupportedVersionKind;
346pub use voter_not_found_error::VoterNotFoundError;
347pub use wakeup_error::WakeupError;
348
349#[cfg(test)]
350mod tests {
351    use super::*;
352    use crate::common::error::{ErrorCode, ErrorHierarchy};
353    use crate::common::protocol::Errors;
354    use crate::producer::ProducerBufferExhaustedError;
355
356    /// `BufferExhaustedException extends TimeoutException` and has no entry of its
357    /// own in `Errors`, so Java's `Errors.forException` walks up and finds
358    /// `REQUEST_TIMED_OUT`. It is therefore retriable — which the class states
359    /// directly, and which no predicate on `Errors` could have expressed.
360    #[test]
361    fn buffer_exhausted_inherits_its_code_from_timeout() {
362        let e = ProducerBufferExhaustedError::new("pool full");
363        assert!(ErrorHierarchy::is_retriable_error(&e));
364        assert_eq!(ErrorCode::error(&e), Errors::RequestTimedOut);
365    }
366
367    /// The 13 classes with no entry in `Errors`: raised client-side, or concrete
368    /// bases whose coded subclasses carry the code instead. Nothing in `Errors`
369    /// can express their ancestry, so it is asserted directly here.
370    ///
371    /// `ErrorCode` gives them `UnknownServerError`, matching Java: a class with
372    /// no entry and no coded superclass falls through `Errors.forException`'s
373    /// walk to `UNKNOWN_SERVER_ERROR`.
374    // Fatality is intentionally NOT checked here: it is not an `ErrorHierarchy`
375    // predicate but `request_utils::RequestUtils::is_fatal_error` over an `Error`. The codeless
376    // fatal classes are covered there instead.
377    #[test]
378    fn codeless_classes_state_their_own_ancestry() {
379        let cases: Vec<(&str, Box<dyn ErrorHierarchy>, &[&str])> = vec![
380            ("ApiError", Box::new(ApiError::new("m")), &["kafka", "api"]),
381            // `BootstrapResolutionException extends KafkaException` (KIP-909).
382            (
383                "BootstrapResolutionError",
384                Box::new(BootstrapResolutionError::new("m")),
385                &["kafka"],
386            ),
387            (
388                "AuthenticationError",
389                Box::new(AuthenticationError::new("m")),
390                &["kafka", "api", "invalid_configuration", "authentication"],
391            ),
392            (
393                "AuthorizationError",
394                Box::new(AuthorizationError::new("m")),
395                &["kafka", "api", "invalid_configuration", "authorization"],
396            ),
397            (
398                "AuthorizerNotReadyError",
399                Box::new(AuthorizerNotReadyError::new("m")),
400                &["kafka", "api", "retriable"],
401            ),
402            (
403                "DisconnectError",
404                Box::new(DisconnectError::new("m")),
405                &["kafka", "api", "retriable"],
406            ),
407            ("InterruptError", Box::new(InterruptError::new("m")), &["kafka"]),
408            (
409                "InvalidOffsetError",
410                Box::new(InvalidOffsetError::new("m")),
411                &["kafka", "api", "invalid_offset"],
412            ),
413            (
414                "RecordDeserializationError",
415                Box::new(RecordDeserializationError::new(
416                    DeserializationErrorOrigin::Value,
417                    crate::common::TopicPartition::new("t".to_string(), 0),
418                    0,
419                    -1,
420                    crate::common::record::TimestampType::NoTimestampType,
421                    None,
422                    None,
423                    None,
424                    "m",
425                )),
426                &["kafka", "serialization"],
427            ),
428            (
429                "SerializationError",
430                Box::new(SerializationError::new("m")),
431                &["kafka", "serialization"],
432            ),
433            (
434                "SslAuthenticationError",
435                Box::new(SslAuthenticationError::new("m")),
436                &["kafka", "api", "invalid_configuration", "authentication"],
437            ),
438            (
439                "TransactionAbortedError",
440                Box::new(TransactionAbortedError::new("m")),
441                &["kafka", "api"],
442            ),
443            ("WakeupError", Box::new(WakeupError::new("m")), &["kafka"]),
444        ];
445
446        for (name, class, expected) in &cases {
447            let actual: Vec<&str> = [
448                ("kafka", class.is_kafka_error()),
449                ("api", class.is_api_error()),
450                ("retriable", class.is_retriable_error()),
451                ("refresh_retriable", class.is_refresh_retriable_error()),
452                ("timeout", class.is_timeout_error()),
453                ("invalid_metadata", class.is_invalid_metadata_error()),
454                ("invalid_configuration", class.is_invalid_configuration_error()),
455                ("unsupported_version", class.is_unsupported_version_error()),
456                ("application_recoverable", class.is_application_recoverable_error()),
457                ("invalid_offset", class.is_invalid_offset_error()),
458                ("consumer_invalid_offset", class.is_consumer_invalid_offset_error()),
459                ("consumer_offset_out_of_range", class.is_consumer_offset_out_of_range_error()),
460                ("out_of_order_sequence", class.is_out_of_order_sequence_error()),
461                ("serialization", class.is_serialization_error()),
462                ("authentication", class.is_authentication_error()),
463                ("authorization", class.is_authorization_error()),
464            ]
465            .into_iter()
466            .filter_map(|(n, holds)| holds.then_some(n))
467            .collect();
468            assert_eq!(&actual, expected, "{name}: ancestry diverges from its Java extends chain");
469        }
470    }
471}