Search code examples
apache-camel

How do I email exception and then return original message to Camel route?


I have a route that validates a bean. If validation fails, I want to email the validation exception and then continue processing the bean. Here's what I have so far:

onException(BeanValidationException.class)
     // the body is an instance of MyClass
    .setBody(simple("${exception}")) 
     // Now it's a String representation of the exception.
    .to("{{route.mail}}")
    .continued(true); //now what? how do I get back the instance of MyClass?
    
    from("{{route.from}}")
    .unmarshal(new BindyCsvDataFormat(MyClass.class))
    .to("bean-validator:priceFeedValidator")
    //continued processing of bean

When validation fails, the above code send the email validation exception. That's good. But when it continues processing the bean, it fails because the message body is no longer a MyClass bean but the exception string.

How can I return back the bean that was there before I called setBody?

Alternatively, is there a way to send the exception in email without overwriting the body of the original flow?


Solution

  • Yeah you can store the body in a temporary exchange property before change it to the exception message when sending the email and restore it afterwards.

    A related question Camel Body: body1 -> body2 -> body1?

    You can also use a bean/processor to send the email, and write a bit of Java code that grab the caused exception from the validation exception, and build the email to send (via a producer template etc) and then avoid changing the message body in the Camel route.