confluent_kafka/common/kafka_error.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//! Java's `KafkaException` base class.
16//!
17//! [`KafkaError`] carries exactly the state `KafkaException` does — a protocol
18//! error code and an optional message — and every specific error struct embeds
19//! one, mirroring Java's subclasses inheriting it.
20//!
21//! It is NOT this crate's base error type. That is [`Error`], the flat enum in
22//! [`super::error`], which `KafkaError` is only one payload of: its
23//! [`KafkaError`](Error::KafkaError) variant stands for a *bare*
24//! `KafkaException`, one with no subclass-specific fields. `Error::Timeout` and
25//! the rest are Kafka errors too — see [`Error::is_kafka_error`] for that test.
26//!
27//! The file keeps its `kafka_error` name because it translates
28//! `org.apache.kafka.common.KafkaException`, as does the C FFI type
29//! `kafka_common_Error_t`.
30
31use std::fmt;
32
33use ambassador::Delegate;
34
35use super::error::{ErrorCode, ErrorHierarchy, ErrorMessage, ErrorName, ErrorSource};
36// Ambassador exports its generated helper macros beside the trait; a
37// `#[delegate]` outside the trait's own module has to import them.
38use super::Error;
39use super::error::ambassador_impl_ErrorMessage;
40use super::protocol::Errors;
41
42/// The base class of all other Kafka errors
43///
44/// # Translation notes
45///
46/// Embedded by each error.
47// Contains the protocol error code and an optional custom message, exactly the
48// state Java's `KafkaException` carries. Fatality is NOT state here: like Java,
49// it is derived from the error's identity, see
50// `request_utils::RequestUtils::is_fatal_error`.
51//
52// Specific error types (e.g. `TopicAuthorizationError`) embed this struct and
53// add their own fields, mirroring Java's error subclasses.
54//
55// Do not confuse this with `Error`, the flat enum that wraps it, or with that
56// enum's `KafkaError` variant, which holds exactly one of these and nothing
57// else. Classification lives on `Error`: Java's `KafkaException` has no
58// `isRetriable()` either. The tests below show both.
59#[derive(Clone, Debug, Delegate)]
60// `target = "self"`: the trait impl is generated from the inherent `message()`
61// below. If that method ever disappeared, this would recurse — and rustc's
62// `unconditional_recursion` lint turns that into a compile error under
63// `#![deny(warnings)]`.
64#[delegate(ErrorMessage, target = "self")]
65#[doc(alias = "org.apache.kafka.common.KafkaException")]
66pub struct KafkaError {
67 /// The protocol error code.
68 error: Errors,
69 /// Custom error message. If `None`, [`Errors::message()`] is used.
70 custom_message: Option<String>,
71 /// The underlying cause — Java's `KafkaException(String, Throwable)`.
72 source: Option<Box<Error>>,
73}
74
75impl KafkaError {
76 // The four constructors below map one-for-one onto Java's four
77 // `KafkaException` constructors — `KafkaException()`,
78 // `KafkaException(String)`, `KafkaException(Throwable)` and
79 // `KafkaException(String, Throwable)` — with a leading `error: Errors`
80 // that has no Java counterpart: it carries what Java's subclass identity
81 // carried, since this struct stands in for the whole base class (CLAUDE.md
82 // §12.3). `error` is therefore in every signature, so the parameter-name
83 // intersection is `{error}` and `new(error)` — Java's no-arg form — keeps the
84 // plain name under CLAUDE.md §2; the rest are suffixed with the Rust
85 // parameters beyond it, in declaration order.
86
87 /// Create a `KafkaError` from an error code with the default message.
88 /// Mirrors Java's no-arg `KafkaException()`.
89 #[doc(alias = "org.apache.kafka.common.KafkaException#KafkaException")]
90 pub(crate) fn new(error: Errors) -> Self {
91 Self { error, custom_message: None, source: None }
92 }
93
94 /// Create a `KafkaError` from an error code with a custom message.
95 /// Mirrors Java's `KafkaException(String message)`.
96 #[doc(alias = "org.apache.kafka.common.KafkaException#KafkaException")]
97 pub(crate) fn with_message(error: Errors, message: impl Into<String>) -> Self {
98 Self { error, custom_message: Some(message.into()), source: None }
99 }
100
101 /// Create a `KafkaError` from an error code, a custom message, and the error
102 /// that caused it. Mirrors Java's `KafkaException(String message, Throwable cause)`.
103 #[doc(alias = "org.apache.kafka.common.KafkaException#KafkaException")]
104 pub(crate) fn with_message_source(error: Errors, message: impl Into<String>, source: Error) -> Self {
105 Self { error, custom_message: Some(message.into()), source: Some(Box::new(source)) }
106 }
107
108 /// Create a `KafkaError` from an error code and the error that caused it,
109 /// keeping the code's default message. Mirrors `KafkaException(Throwable cause)`.
110 #[doc(alias = "org.apache.kafka.common.KafkaException#KafkaException")]
111 pub(crate) fn with_source(error: Errors, source: Error) -> Self {
112 Self { error, custom_message: None, source: Some(Box::new(source)) }
113 }
114
115 /// Returns the underlying cause, if any: Java's `getCause()`.
116 #[doc(alias = "rust-only")]
117 pub fn source(&self) -> Option<&Error> {
118 self.source.as_deref()
119 }
120
121 /// The protocol error code. Only the C bindings read it back.
122 #[cfg_attr(not(feature = "ffi"), expect(dead_code))]
123 pub(crate) fn error(&self) -> Errors {
124 self.error
125 }
126
127 /// Returns the error message: the custom message if set, otherwise the default message of
128 /// the error code. Java's `getMessage()`.
129 #[doc(alias = "rust-only")]
130 pub fn message(&self) -> &str {
131 match &self.custom_message {
132 Some(msg) => msg,
133 None => self.error.message(),
134 }
135 }
136}
137
138impl ErrorSource for KafkaError {
139 fn source(&self) -> Option<&Error> {
140 self.source.as_deref()
141 }
142}
143
144impl fmt::Display for KafkaError {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 write!(f, "{}", self.message())
147 }
148}
149
150impl std::error::Error for KafkaError {
151 // Wired to the stored source. This impl used to be empty, so `source()`
152 // answered `None` even when a cause was present; Java's
153 // `KafkaException(String, Throwable)` keeps it.
154 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
155 self.source.as_deref().map(|e| e as &(dyn std::error::Error + 'static))
156 }
157}
158
159impl ErrorCode for KafkaError {
160 fn error(&self) -> Errors {
161 self.error
162 }
163}
164
165// Hand-written rather than emitted by `error_name_impl!` in `super::error`: that
166// macro covers the payloads declared in their own files, and this one is
167// declared right here.
168impl ErrorName for KafkaError {
169 fn name(&self) -> &'static str {
170 "KafkaError"
171 }
172}
173
174/// A *bare* `KafkaException`: `Error::KafkaError` is now only reached for
175/// [`Errors::None`], since every other code maps to its own class through
176/// [`Errors::error`]. So it answers for `KafkaException` itself and nothing
177/// else — in particular NOT [`is_api_error`](ErrorHierarchy::is_api_error),
178/// because `KafkaException` is the parent of `ApiException`, not an instance of
179/// it. The remaining predicates take the trait's `false`.
180impl ErrorHierarchy for KafkaError {
181 fn is_kafka_error(&self) -> bool {
182 true
183 }
184}
185
186#[cfg(test)]
187mod tests {
188 use crate::common::Error;
189
190 #[test]
191 fn test_base_carries_message_and_source() {
192 let err = Error::kafka_message_source("send failed", Error::timeout("expired"));
193 let base = err.kafka_error().expect("a bare Kafka error embeds a KafkaError");
194 assert_eq!(base.message(), "send failed");
195 assert_eq!(base.source().map(Error::message), Some("expired"));
196 }
197
198 #[test]
199 fn test_classification_lives_on_error() {
200 assert!(Error::timeout("expired").is_retriable_error());
201 assert!(!Error::kafka().is_retriable_error());
202 }
203}