3 #include <kafka/Project.h>
5 #include <kafka/RdKafkaHelper.h>
7 #include <librdkafka/rdkafka.h>
10 #include <system_error>
15 struct ErrorCategory:
public std::error_category
17 const char* name() const noexcept
override {
return "KafkaError"; }
18 std::string message(
int ev)
const override {
return rd_kafka_err2str(
static_cast<rd_kafka_resp_err_t
>(ev)); }
20 template <
typename T =
void>
21 struct Global {
static ErrorCategory category; };
25 ErrorCategory ErrorCategory::Global<T>::category;
35 explicit Error(rd_kafka_error_t* error =
nullptr): _rkError(error, RkErrorDeleter) {}
37 explicit Error(rd_kafka_resp_err_t respErr): _respErr(respErr) {}
39 Error(rd_kafka_resp_err_t respErr, std::string
message,
bool fatal =
false)
40 : _respErr(respErr), _message(std::move(
message)), _isFatal(fatal) {}
47 if (
this == &error)
return *
this;
51 _respErr =
static_cast<rd_kafka_resp_err_t
>(error.
value());
52 _message = error._message;
63 explicit operator bool()
const {
return static_cast<bool>(
value()); }
68 explicit operator std::error_code()
const
70 return {
value(), ErrorCategory::Global<>::category};
83 return static_cast<int>(_rkError ? rd_kafka_error_code(_rkError.get()) : _respErr);
91 return _message ? *_message :
92 (_rkError ? rd_kafka_error_string(_rkError.get()) : rd_kafka_err2str(_respErr));
100 std::ostringstream oss;
102 oss << rd_kafka_err2str(static_cast<rd_kafka_resp_err_t>(
value())) <<
" [" <<
value() <<
"]" << (
isFatal() ?
" fatal" :
"");
104 if (
auto retriable =
isRetriable()) oss <<
" | " << (*retriable ?
"retriable" :
"non-retriable");
105 if (_message) oss <<
" | " << *_message;
115 return _rkError ? rd_kafka_error_is_fatal(_rkError.get()) : _isFatal;
123 return _rkError ? rd_kafka_error_is_retriable(_rkError.get()) : _isRetriable;
135 return _rkError ? rd_kafka_error_txn_requires_abort(_rkError.get()) :
false;
139 rd_kafka_error_shared_ptr _rkError;
140 rd_kafka_resp_err_t _respErr{};
141 Optional<std::string> _message;
142 bool _isFatal =
false;
143 bool _txnRequiresAbort =
false;
144 Optional<bool> _isRetriable;
Unified error type.
Definition: Error.h:32
bool isFatal() const
Fatal error indicates that the client instance is no longer usable.
Definition: Error.h:113
bool transactionRequiresAbort() const
Show whether the error is an abortable transaction error.
Definition: Error.h:133
std::string message() const
Readable error string.
Definition: Error.h:89
int value() const
Obtains the underlying error code value.
Definition: Error.h:81
Optional< bool > isRetriable() const
Show whether the operation may be retried.
Definition: Error.h:121
std::string toString() const
Detailed error string.
Definition: Error.h:98