How to handle exception using onException() in Spring Boot Camel

1.1k Views Asked by At

Spring boot Apache Camel-Java DSL app reads messages from Kafka topic.

@Component
public class KafkaTopicService extends RouteBilder {

    public void configure(){
       from("kafka:myTopic?brokers=localhost:9092")
           .log("Message received from Kafka: ${body}")}
}

If I stop Kafka I get org.apache.kafka.common.errors.DisconnectException

I looked into onException(...class).handled(true) but Im not sure how to implement handling of the exception in my code. Can someone give me few implementation examples? What options are available? For example logging the message or reattempting to read message? Documentation also mentions Quarkus. Do I need Quarkus to use onException()?

1

There are 1 best solutions below

0
On

You can do something like (have not tried running it so please take care of any typos)

@Component
public class KafkaTopicService extends RouteBilder {

    public void configure(){

        onException(org.apache.kafka.common.errors.DisconnectException.class)
            .log("Error connecting kafka");

        from("kafka:myTopic?brokers=localhost:9092&bridgeErrorHandler=true")
           .log("Message received from Kafka: ${body}")}
}

Please note that I have added bridgeErrorHandler=true. Normally exception handling happens after from. In most of the case using bridgeErrorHandler we can use onException function for those.

Also note that I have defined onException outside your route, so the exception handling logic which you add would be global and applicable to all routes wherever you encounter DisconnectException