Apache Camel: Throw Exception from Sub-Route to Previous Route
December 30, 2015
By default, each Apache Camel route has its own error handler, meaning each independently catches and handles Exceptions thrown within it. But, what if a “parent route” needs to catch and handle Exceptions thrown by a sub-route? Here’s one approach:
<route id="fooA">
<from .../>
<onException>
...
</onException>
...
<to uri="direct:fooB"/>
</route>
<route id="fooB">
<from uri="direct:fooB"/>
CODE THROWS AN EXCEPTION
<to .../>
</route>
As is, the above code will result in the DefaultErrorHandler handling the Exception, but within fooB! Since fooB simply consumes a direct: endpoint, this only results in a stacktrace in the console.
Instead, the following utilizes Camel’s NoErrorHandler on fooB, effectively allowing the Exception to propagate up to fooA’s onException.
<errorHandler id="noErrorHandler" type="NoErrorHandler" />
<route id="fooA">
<from .../>
<onException>
...
</onException>
...
<to uri="direct:fooB"/>
</route>
<route id="fooB" errorHandlerRef="noErrorHandler">
<from uri="direct:fooB"/>
CODE THROWS AN EXCEPTION
<to .../>
</route>