And since I improved (hmm added) the documentation to the Apache Camel wiki I might as well do a blog about it as well :)
Using try catch finally in Apache Camel
Camel supports the Java equivalent of try .. catch and finally directly in the DSL.
It aims to work like its Java sisters but with more power. Especially in Camel 2.0 where we gave this feature an overhaul.
In Camel we prefix the keywords with do to avoid having same keyword as Java. So we have:
- end to end the block in Java DSL (Spring DSL have the </doTry> tag to end)
The doCatch in Camel is empowered over its Java sister. First of all you can define multiple exceptions to catch in a single block. And secondly you can attach a onWhen predicate to signal if the catch should trigger or not at runtime.
To simulate rehrowing an exception from a doCatch you should use the handled predicate. If its evaluated to false Camel will reattach the exception on the Exchange.
And just like Java the order in which you have multiple doCatch blocks matter. Camel will iterate from the top going down and use the first doCatch that matches the exception and if the onWhen predicate matches as well (if any provided). This is the same behavior as the Exception Clause.
Using try .. catch .. finally in Java DSL
In the route below we have all keywords in action. As the code is based on a unit test we route using Mock.
And here we have the same route in Spring DSL:
<!-- here the try starts. its a try .. catch .. finally just as regular java code -->
<!-- catch multiple exceptions -->
There are more samples in the Camel Try Catch Finally documentation that also demonstrates the onWhen and handled predicates and what they are used for.
The overhaul was needed as it really brings the power of using try .. catch .. finally up to the same level as the exception clauses and error handlers in Camel. But having them right at your fingertips as regular Java like try .. catch .. finally brings the gaps from thinking Java to EIP patterns a bit closer.
PS: Mind that the static wiki documentation takes a few hours to be updated based on the dynamic changes I recently added, so some of the links might not work until then.