The correct way to handle kafka exception?
Hi. I am new to kafka-python, and wondering
- As a forever-running server, what is the correct way to handle kafka exception.
- Since I am using the async-producer, can I know whether every message has sent to kafka or not.
Is it correct code?
from kafka import KafkaProducer
producer = None
def handle_message(msg):
if producer is None:
producer = KafkaProducer(bootstrap_servers='localhost:1234')
try:
producer.send('foobar', msg)
except Exception, e:
producer.close()
producer = None
#Return False will resend the message.
return False
return True
producer.send returns a future. You should check futures. producer.send may raise a KafkaTimeoutError, but only in rare circumstances. To check whether the message itself was sent correctly, try future.get(timeout). There is more information about futures here:
https://github.com/dpkp/kafka-python/blob/master/kafka/future.py
Unfortunately we dont have great documentation on the futures on RTD or in docstrings.
@dpkp
Thanks for reply, I also notice that I can add callbacks to the future to do exception handling. That's what I expect. Thank you.
How do you add exception handling to future when the obj is created by the lib
future.add_errback
f = producer.send(...)
<- error happens here
f.add_errback(..) # I assume this won't work?