Search code examples
spring-kafka

How to use ContainerStoppingErrorHandler in @KafkaListener to terminate application incase of Kafka server DisconnectException


I want to handle the Server DisconnectException and terminate the application when the server DisconnectException occurs

how to catch this error and stop the application?

@KafkaListener(topics = { "${kafka.status-topic}", "${kafka.start-topic}" }, containerFactory = "kafkaListenerContainerFactory")
public void listen(@Payload final String message,
        @Header(KafkaHeaders.RECEIVED_TOPIC) final String topic) {
    log.debug("Received '{}'-message {} from Kafka", topic, message);
    LinkedList<IMessageListener> topicListeners = listeners.get(topic);
    for (final IMessageListener l : topicListeners) {
        // call listeners in a separate thread
        executor.execute(new Runnable() {
            @Override
            public void run() {
                l.messageReceived(topic, message);
            }
        });
    }
}

Solution

  • You can try catching the exception and then calling System.exit(0) inside catch block