Spina
Spina

Reputation: 9346

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

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.

Upvotes: 5

Views: 20750

Answers (3)

Henryk Konsek
Henryk Konsek

Reputation: 9168

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();

Upvotes: 8

Christian Schneider
Christian Schneider

Reputation: 19606

You could use a bean that checks for null and throws an exception in case of null. So you could handle this case in your exception handling.

Upvotes: 0

Claus Ibsen
Claus Ibsen

Reputation: 55750

You can use an interceptor, such as interceptFrom with a when, to check for the empty bod, as there is an example of here: http://camel.apache.org/intercept

And then use stop to indicate no further processing:

interceptFrom("servlet*").when(body().isNull()).to("direct:syntaxError").stop();

Upvotes: 7

Related Questions