You can use the Exception Clause in the Java DSL to specify the error handling you require on a per exception type basis using the onException() method.
To get started we give quick sample before digging into how it works.
Here if the processing of seda:inputA or seda:inputB cause a ValidationException to be thrown (such as due to the XSD validation of the Validation component or the Relax NG Compact syntax validation of the Jing component), then the message will be sent to activemq:validationFailed queue.
You can define multiple onException clauses for different behavior
Exception clauses is scoped as either:
Where the global are the simplest and most easy to understand. In the advanced section we dig into the route specific and even combining them. However
How does Camel select which clause should handle a given thrown Exception
This is best illustrated with an exception:
In the sample above we have defined two exceptions in which IOException is first, so Camel will pickup this exception if there is a match. IOException that is more general is selected then.
So if an exception is thrown with this hierarchy:
Then Camel will try testing the exception in this order: FileNotFoundException, IOException, OrderFailedException and RuntimeCamelException.
If we add a third onException clause with the
Then with the previous example Camel will now use the last
Now a new situation if this exception was thrown instead:
And this last sample demonstrates the
Since SocketException is an instanceof IOException, Camel will select the
Configuring RedeliveryPolicy (redeliver options)
RedeliveryPolicy requires to use the Dead Letter Channel as the Error Handler. Dead Letter Channel supports attempting to redeliver the message exchange a number of times before sending it to a dead letter endpoint. See Dead Letter Channel for further information about redeliver and which redeliver options exists.
Sometimes you want to configure the redelivery policy on a per exception type basis. By default in the top examples, if a ValidationException occurs then the message will not be redelivered; however if some other exception occurs (IOException or whatelse) the route will be retried according to the settings from the Dead Letter Channel.
However if you want to customize any methods on the RedeliveryPolicy object, you can do this via the fluent API. So lets retry in case of ValidationException up till two times.
And the spring DSL:
You can customize any of the RedeliveryPolicy so we can for instance set a different delay of 5000 millis:
Point of entry for redelivery attempts
All redelivery attempts start at the point of the failure. So the route:
Will retry from processor2 - not the complete route.
Available as of Camel 1.5.1 or later
Asynchronous delayed redelivery
Available as of Camel 2.4
From Camel 2.4 onwards Camel has a feature to not block while waiting for a delayed redelivery to occur. However if you use transacted routes then Camel will block as its mandated by the transaction manager to execute all the work in the same thread context. You can enable the non blocking asynchronous behavior by the
By default the error handler will create and use a scheduled thread pool to trigger redelivery in the future. From Camel 2.8 onwards you can configure the
Catching multiple exceptions
Available as of Camel 1.5
In Camel 1.5 the exception clauses has been renamed to onException and it also supports multiple exception classes:
And in Spring DSL you just add another exception element:
Using a processor as failure handler
We want to handle certain exceptions specially so we add a onException clause for that exception.
So what happens is that whenever a
Notice how we get the caused by exception using a property on the Exchange. This is where Camel stores any caught exception during processing. So you can fetch this property and check what the exception message and do what you want. In the code above we just route it to a mock endpoint using a producer template from Exchange.
Marking exceptions as being handled
Available as of Camel 1.5
Using onException to handle known exceptions is a very powerful feature in Camel. However prior to Camel 1.5 you could not mark the exception as being handled, so the caller would still receive the caused exception as a response. In Camel 1.5 you can now change this behavior with the new handle DSL. The handle is a Predicate that is overloaded to accept three types of parameters:
For instance to mark all
Example using handled
In this route below we want to do special handling of all OrderFailedException as we want to return a customized response to the caller. First we setup our routing as:
Then we have our service beans that is just plain POJO demonstrating how you can use Bean Integration in Camel to avoid being tied to the Camel API:
And finally the exception that is being thrown is just a regular exception:
So what happens?
If we sent an order that is being processed OK then the caller will receive an Exchange as reply containing
If the order could not be processed and thus an OrderFailedException was thrown the caller will not receive this exception (as opposed to in Camel 1.4, where the caller received the OrderFailedException) but our customized response that we have fabricated in the
Using handled with Spring DSL
The same route as above in Spring DSL:
Handling and sending a fixed response back to the client
In the route above we handled the exception but routed it to a different endpoint. What if you need to alter the response and send a fixed response back to the original caller (the client). No secret here just do as you do in normal Camel routing, use transform to set the response, as shown in the sample below:
We modify the sample slightly to return the original caused exception message instead of the fixed text Sorry:
And we can use the Simple language to set a readable error message with the caused excepetion message:
Handle and continue exceptions
Available as of Camel 2.3
In Camel 2.3 we introduced a new option
For instance to just ignore and continue if the
You can maybe compare continued with a having a
Example using continued
In this route below we want to do special handling of all IllegalArgumentException as we just want to continue routing.
And the same example in Spring XML:
What is the difference between handled and continued?
If handled is true, then the thrown exception will be handled and Camel will not continue routing in the original route, but break out. However you can configure a route in the
If continued is true, then Camel will catch the exception and in fact just ignore it and continue routing in the original route. However if you have a route configured in the
Available as of Camel 2.0
For instance if you have this route:
The route listen for JMS messages and validates, transforms and handle it. During this the Exchange payload is transformed/modified. So in case something goes wrong and we want to move the message to another JMS destination, then we can add an onException. But when we move the Exchange to this destination we do not know in which state the message is in. Did the error happen in before the transformOrder or after? So to be sure we want to move the original input message we received from
Then the messages routed to the
useOriginalMessage with Spring DSL
The useOriginalMessage option is defined as a boolean attribute on the <onException> XML tag in Spring DSL. So the definition above would be:
Advanced Usage of Exception Clause
Using global and per route exception clauses
Camel supports quite advanced configuration of exception clauses.
You can define exception clauses either as:
We start off with the sample sample that we change over time. First off we use only global exception clauses:
In the next sample we change the global exception policies to be pure route specific.
And now it gets complex as we combine global and route specific exception policies as we introduce a 2nd route in the sample:
Notice that we can define the same exception MyFunctionalException in both routes, but they are configured differently and thus is handled different depending on the route. You can of course also add a new onException to one of the routes so it has an additional exception policy.
And finally we top this by throwing in a nested error handler as well, as we add the 3rd route shown below:
Using fine grained selection using onWhen predicate
Available as of Camel 1.5.1 or later
You can attach an Expression to the exception clause to have fine grained control when a clause should be selected or not. As it's an Expression you can use any kind of code to perform the test. Here is a sample:
In the sample above we have two onException's defined. The first has an onWhen expression attached to only trigger if the message has a header with the key user that is not null. If so this clause is selected and is handling the thrown exception. The 2nd clause is a for coarse gained selection to select the same exception being thrown but when the expression is evaluated to false. Notice: this is not required, if the 2nd clause is omitted, then the default error handler will kick in.
Using onRedelivery processor
Available as of Camel 2.0
Dead Letter Channel has support for onRedelivery to allow custom processing of a Message before its being redelivered. It can be used to add some customer header or whatnot. In Camel 2.0 we have added this feature to Exception Clause as well, so you can use per exception scoped on redelivery. Camel will fallback to use the one defined on Dead Letter Channel if any, if none exists on the Exception Clause. See Dead Letter Channel for more details on onRedelivery.
In the code below we want to do some custom code before redelivering any IOException. So we configure an onException for the IOException and set the onRedelivery to use our custom processor:
And in our custom processor we set a special timeout header to the message. You can of course do anything what you like in your code.
Using onRedelivery in Spring DSL
In Spring DSL you need to use the onRedeliveryRef attribute to refer to a spring bean id that is your custom processor:
And our processor is just a regular spring bean (we use $ for the inner class as this code is based on unit testing)
Using fine grained retry using retryWhile predicate
Available as of Camel 2.0
When you need fine grained control for determining if an exchange should be retried or not you can use the retryWhile predicate. Camel will redeliver until the predicate returns false.
Where the bean myRetryHandler is computing if we should retry or not:
Using custom ExceptionPolicyStrategy
Available in Camel 1.4
The default ExceptionPolicyStrategy in Camel should be sufficient in nearly all use-cases (see section How does Camel select which clause should handle a given thrown Exception). However if you need to use your own this can be configued as the sample below illustrates:
Using our own strategy MyPolicy we can change the default behavior of Camel with our own code to resolve which ExceptionType from above should be handling the given thrown exception.
Using the exception clause in Spring DSL
You can use all of the above mentioned exception clause features in the Spring DSL as well. Here are a few examples: