kafka-python icon indicating copy to clipboard operation
kafka-python copied to clipboard

The correct way to handle kafka exception?

Open hzhaop opened this issue 10 years ago • 5 comments

Hi. I am new to kafka-python, and wondering

  1. As a forever-running server, what is the correct way to handle kafka exception.
  2. 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

hzhaop avatar Aug 15 '16 02:08 hzhaop

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 avatar Aug 15 '16 16:08 dpkp

@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.

hzhaop avatar Aug 16 '16 02:08 hzhaop

How do you add exception handling to future when the obj is created by the lib

siyuanh avatar Oct 17 '17 16:10 siyuanh

future.add_errback

dpkp avatar Oct 17 '17 17:10 dpkp

f = producer.send(...)

<- error happens here

f.add_errback(..) # I assume this won't work?

siyuanh avatar Oct 18 '17 17:10 siyuanh