Reputation: 1888
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
{
@Autowired
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:
try
{
manualKafkaBetsProducer.send(bet);
}
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.
Upvotes: 1
Views: 4200
Reputation: 262474
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.
Upvotes: 2