Camel Exception Handling With Example

Camel Exception Handling With Example In simple steps.


In our example we will learn how can camel handle specific exception.How policy can be defined for exception during handling.As a broker we are using ActiveMQ.So we have assumed you have ActiveMQ in your local machine.

Camel error handler is applicable for all exception but if we want to define a separate policy for specific exception then we use onException.

  • In eclipse create a maven project MyFirstCamelErrorHandler as we created in earlier page and right click on src/main/java to create package. New -> package



  • Give any name for example com.preparationforinterview.errorhandler.javadsl and click on Finish



  • Right click on package and create a java class for example Executor.



  • Right click on package and create one more java class for example ErrorHandlerRoute.



  • Right click on package and create a java class for example MyProcessor.



  • Add following dependency in pom.xml file.you can use any latest version.

  •  	
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-core</artifactId>
    			<version>2.13.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.camel</groupId>
    			<artifactId>camel-jms</artifactId>
    			<version>2.5.0</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.activemq</groupId>
    			<artifactId>activemq-core</artifactId>
    			<version>5.3.2</version>
    		</dependency>
    
  • Run mvn:install from command prompt or if you are using Eclipse right click on pom.xml and run mvn install.It will download camel jars

  • Copy below code in MyProcessor.

  •  		
    package com.preparationforinterview.errorhandler.javadsl;
    
    import java.io.IOException;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    
    public class MyProcessor implements Processor{
    
    	public void process(Exchange exchange) throws IOException {
    		System.out.println("processing " + exchange.getIn().getBody(String.class));
    		exchange.getIn().setBody("Hello Good Morning");
    		throw new IOException();
    		
    	}
    
    }
    

    Explain

    We created processor and printing incoming message and at the same time we are changing out going message so that we can show that during error handling what happens to outgoing message and sending an exception so that our onException can trigger.

  • Copy below code in ExceptionProcessor.

  •  		
    package com.preparationforinterview.errorhandler.javadsl;
    
    import org.apache.camel.Exchange;
    import org.apache.camel.Processor;
    
    public class ExceptionProcessor  implements Processor{
    
    	public void process(Exchange exchange) throws Exception {
    		System.out.println("processing " + exchange.getIn().getBody(String.class));
    		exchange.getIn().setBody("Hello Good Morning after onException");
    	}
    
    }
    

    Explain

    This processor will be executed when onException is triggered..

  • Copy below code in ErrorHandlerRoute.

  •  		
    package com.preparationforinterview.errorhandler.javadsl;
    
    import java.io.IOException;
    import org.apache.camel.builder.RouteBuilder;
    
    public class ErrorHandlerRoute extends RouteBuilder {
    
    	@Override
    	public void configure() throws Exception {
    		onException(IOException.class).handled(true)
    				.process(new ExceptionProcessor());
    
    		from("jms:queue:input").process(new MyProcessor()).to(
    				"jms:queue:preparationforinterview");
    	}
    }
    

    Explain

    To create a route in camel we need to extend RouteBuilder class and override configure method.In configure method we define our route.In above example we can read it as from input queue take message and call our processor which will throw IOException.We will not getting any message to our output queue preparationforinterview.Here jms: is called endpoint.

    In onException we have mentioned our policy that if any IOException occurs then onException will handle it and call to ExceptionProcessor for further processing. By default handle is false so onException will not handle it.

  • Copy below code in Executor.

  •  	
    package com.preparationforinterview.errorhandler.javadsl;
    
    import javax.jms.ConnectionFactory;
    
    import org.apache.activemq.ActiveMQConnectionFactory;
    import org.apache.camel.CamelContext;
    import org.apache.camel.component.jms.JmsComponent;
    import org.apache.camel.impl.DefaultCamelContext;
    
    public class Executor {
    
    	public static void main(String args[]) throws Exception {
    		CamelContext context = new DefaultCamelContext();
    		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory();
    		context.addComponent("jms",
    				JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
    		context.addRoutes(new ErrorHandlerRoute());
    		context.start();
    		Thread.sleep(100000);
    		context.stop();
    	}
    
    }
    

    Explain

    First we need to create CamelContext. It has many implementation but we are using DefaultCamelContext.Camel provides ConnectionFactory but to which provider we need to connect we have to give that here we are using ActiveMQ so give ActiveMQConnectionFactory and add it to camel JmsComponent and link it to "jms" name ,you can use any name but whatever you will give, use same in ErrorHandlerRoute router class.After that add route in camel context.Its like registry of route in CamelContext, till that part we have just configured route in CamelContext but until and unless we start CamelContext it will not execute route.We kept Thread.sleep(1000) so that camel gets enough time to copy file from input to output folder.

    To check the output right click on Executor.java and run it.It will show as below.


    Send a message say Hello World


    When we send message to input queue, route will pick message and will call our MyProcessor ,processor changing this message to Hello Good Morning.As per policy, when IOException will be thrown it will call ExceptionProcessor, so on console we get following message.One from MyProcessor and other from ExceptionProcessor


    Similarly if we want to do by spring

     	
    	<bean id="exceptionProcessor" class="com.preparationforinterview.errorhandler.javadsl.ExceptionProcessor"/>
    	
    	<camelContext xmlns="http://camel.apache.org/schemas/spring">
    	<onException>
    	<exception>java.io.IOException</exception>
    	<handled><constant>true</constant></handled>
    	<process ref="exceptionProcessor"/>
    	</onException>
    	</camelContext>
    	
    To run the program from command prompt, open command prompt and go to project location and run below command.
    mvn compile exec:java -Dexec.mainClass=com.preparationforinterview.errorhandler.javadsl.Executor

    Note:

  • If we want to skip specific exception then use continued(true)
  • Copy below code in ErrorHandlerRoute.

  •  		
    	package com.preparationforinterview.errorhandler.javadsl;
    	
    	import java.io.IOException;
    	import org.apache.camel.builder.RouteBuilder;
    	
    	public class ErrorHandlerRoute extends RouteBuilder {
    	
    		@Override
    		public void configure() throws Exception {
    		/*	onException(IOException.class).handled(true)
    					.process(new ExceptionProcessor());*/
    			
    			onException(IOException.class).continued(true);
    	
    			from("jms:queue:input").process(new MyProcessor()).to(
    					"jms:queue:preparationforinterview");
    		}
    	}
    
    

    After executing above ErrorHandlerRoute IOException will be skipped and preparationforinterview will get message.





Download source code

Camel Exception Handling With Example Using Java DSL


Visit Others Links

Camel Introduction
Camel Setup
File Copy Example Using Camel
File Copy Example In Camel Using Spring
JMS Message Transfer Example Using Camel
JMS Message Transfer Example In Camel Using Spring
Processor In Camel
Object to JSON Transfer Example Using Spring In Camel
Camel With Bean Injection Example Using Spring DSL
Camel With Bean Injection Registry Example Using Java DSL
Camel Bean Parameter Binding Example Using Java DSL
Camel Error Handling With Redelivery Example Using Java DSL
Camel Exception Handling With Example Using Java DSL
Camel JUnit Test With Example Using Java DSL
Camel JUnit Test With Example Using Spring DSL
Camel Unit Test With Mock Component Example
Camel With Stream Component Example
Camel In-Memory Messaging Example Using Direct
Camel With Timer And Quartz Example
Camel Aggregator EIP Example
Camel Splitter EIP Example
Camel Routing Slip EIP Example
Camel Dynamic Router EIP Example
Camel Load Balancer EIP Example
Top Camel Interview Question
© 2019 PreparationForInterview.com