Handling Kafka timeout exception Java

I am using Kafka in my app and I want to handle timeout exceptions during kafka send message. I tried to do next: on callback throw Runtime exception and catch it in the method call.

This is kafka call:

public final class ManualKafkaBetsProducer implements IKafkaBetsProducer
    private KafkaTemplate<ReportsBetKey, IReportsBet> template;

    public void send(IReportsBet bet)
        template.send(MessageBuilder.withPayload(bet).setHeader(KafkaHeaders.TOPIC, kafkaBetsTopicName)
                .setHeader(KafkaHeaders.MESSAGE_KEY, new ReportsBetKey(bet)).build())
                .addCallback(res -> logger.debug("Message {} send OK"), ex -> {
                    throw new RuntimeException(ex);

And this is method call:

catch (Exception ex)
     return TransactionResultType.GENERAL_ERROR.name();

The problem is: when timeout expeption occurs, it doesn’t go to the catch block. When some other error happens, it works ok. Any ideas how to handle this? Thank you.


Your send method returns a ListenableFuture<SendResult>.

If you want to get an exception on the sending thread if the send failed, you could wait for this future to complete (by calling get() on it) and check the result.

The callback is useful if you don’t want the sending thread to wait. It gives you chance to have another thread pick up the results later.