Tuesday, August 17, 2010

Camel exception handling overview

Here are some notes on adding Camel (v2.3) exception handling to a JavaDSL route.  There are various approaches/options available.  These notes cover the important distinctions between approaches...

default handling
The default mode uses the DefaultErrorHandler strategy which simply propagates any exception back to the caller and ends the route immediately.  This is rarely the desired behavior, at the very least, you should define a generic/global exception handler to log the errors and put them on a queue for further analysis (during development, testing, etc).


This approach mimics the Java for exception handling and is designed to be very readable and easy to implement.  It inlines the try/catch/finally blocks directly in the route and is useful for route specific error handling.

        .process(new MyProcessor())

This approach defines the exception clause separately from the route.  This makes the route and exception handling code more readable and reusable.  Also, the exception handling will apply to any routes defined in its CamelContext.

    .process(new MyProcessor())


These APIs provide valuable control over the flow.   Adding handled(true) tells Camel to not propagate the error back to the caller (should almost always be used).  The continued(true) tells Camel to resume the route where it left off (rarely used, but powerful).  These can both be used to control the flow of the route in interesting ways, for example...

    .process(new MyProcessor())

//send the exception back to the client (rarely used, clients need a meaningful response)
    .handled(false)    //default
    .log("error sent back to the client");

//send a readable error message back to the client and handle the error internally

//ignore the exception and continue the route (can be dangerous, use wisely)

using a processor for more control
If you need more control of the handler code, you can use an inline Processor to get a handle to the exception that was thrown and write your own handle code...

    .process(new Processor() {
         public void process(Exchange exchange) throws Exception {
               Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
               //log, email, reroute, etc.

Overall, the exception handling is very flexible and can meet almost any scenario you can come up with.  For the sake of focusing on the basics, many advanced features haven't been covered here.
For more details, see these pages on Camel's site...


No comments:

Post a Comment