Can this handling of a null body in Apache Camel be more elegant?

Spina picture Spina · May 25, 2012 · Viewed 13k times · Source

I'm new to Camel and trying to learn idioms and best practices. I am writing web services which need to handle several different error cases. Here is my error handling and routing:

onException(JsonParseException.class).inOut("direct:syntaxError").handled(true);
onException(UnrecognizedPropertyException.class).inOut("direct:syntaxError").handled(true);

// Route service through direct to allow testing.
from("servlet:///service?matchOnUriPrefix=true").inOut("direct:service");
from("direct:service")
    .choice()
        .when(body().isEqualTo(null))
            .inOut("direct:syntaxError")
        .otherwise()
            .unmarshal().json(lJsonLib, AuthorizationParameters.class).inOut("bean:mybean?method=serviceMethod").marshal().json(lJsonLib);

As you can see, I have special handling (content based routing) to deal with a request with a null body. Is there a way to handle this more elegantly? I'm writing several services of this type and it seems like they could be much cleaner.

Answer

Henryk Konsek picture Henryk Konsek · May 27, 2012

Using body().isNull() expression in content-based routing to redirect null message to Dead Letter Channel is even more than elegant :) . Please note that message redirected to the DLC will still contain headers so you can easily analyze the reason of delivery failure later on.

choice().
   when(body().isNull()).to("jms:deadLetterChannel").
   otherwise().to("jms:regularProcessing").
endChoice();