Skip to content

Commit 01c1481

Browse files
committed
Use reflection to avoid multiple errno definitions
1 parent 6603088 commit 01c1481

File tree

2 files changed

+14
-27
lines changed

2 files changed

+14
-27
lines changed

kafka/common.py

+12-24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import inspect
2+
import sys
13
from collections import namedtuple
24

35
###############
@@ -79,9 +81,6 @@ class KafkaError(RuntimeError):
7981
class BrokerResponseError(KafkaError):
8082
pass
8183

82-
class NoError(BrokerResponseError):
83-
errno = 0
84-
message = 'SUCCESS'
8584

8685
class UnknownError(BrokerResponseError):
8786
errno = -1
@@ -201,27 +200,16 @@ class KafkaConfigurationError(KafkaError):
201200
pass
202201

203202

204-
kafka_errors = {
205-
-1 : UnknownError,
206-
0 : NoError,
207-
1 : OffsetOutOfRangeError,
208-
2 : InvalidMessageError,
209-
3 : UnknownTopicOrPartitionError,
210-
4 : InvalidFetchRequestError,
211-
5 : LeaderNotAvailableError,
212-
6 : NotLeaderForPartitionError,
213-
7 : RequestTimedOutError,
214-
8 : BrokerNotAvailableError,
215-
9 : ReplicaNotAvailableError,
216-
10 : MessageSizeTooLargeError,
217-
11 : StaleControllerEpochError,
218-
12 : OffsetMetadataTooLargeError,
219-
13 : StaleLeaderEpochCodeError,
220-
}
203+
def _iter_broker_errors():
204+
for name, obj in inspect.getmembers(sys.modules[__name__]):
205+
if inspect.isclass(obj) and issubclass(obj, BrokerResponseError) and obj != BrokerResponseError:
206+
yield obj
221207

222208

223-
def check_error(response):
224-
error = kafka_errors.get(response.error, UnknownError)
225-
if error is not NoError:
226-
raise error(response)
209+
kafka_errors = dict([(x.errno, x) for x in _iter_broker_errors()])
210+
227211

212+
def check_error(response):
213+
if response.error:
214+
error_class = kafka_errors.get(response.error, UnknownError)
215+
raise error_class(response)

test/test_client.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,8 @@
1010
ProduceRequest, MetadataResponse,
1111
BrokerMetadata, TopicMetadata, PartitionMetadata,
1212
TopicAndPartition, KafkaUnavailableError,
13-
LeaderNotAvailableError, NoError,
14-
UnknownTopicOrPartitionError, KafkaTimeoutError,
15-
ConnectionError
13+
LeaderNotAvailableError, UnknownTopicOrPartitionError,
14+
KafkaTimeoutError, ConnectionError
1615
)
1716
from kafka.conn import KafkaConnection
1817
from kafka.protocol import KafkaProtocol, create_message

0 commit comments

Comments
 (0)