Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package eu.janbednar.stackoverflow.camelTest;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Assert;
import org.junit.Test;
public class DoTryHandling extends CamelTestSupport {
class ThrowExceptionProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
if (exchange.getIn().getBody(String.class).equals("throw")){
throw new IllegalStateException("Test exception");
} else {
exchange.getIn().setBody("Processed OK");
}
}
}
@Override
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:withProcessor")
.doTry()
.process(new ThrowExceptionProcessor())
.doCatch(Exception.class)
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
final Throwable ex = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);
exchange.getIn().setBody(ex.getMessage());
}
})
.end();
from("direct:withSimple")
.doTry()
.process(new ThrowExceptionProcessor())
.doCatch(Exception.class)
.transform().simple("${exception.message}")
.end();
from("direct:withValueBuilder")
.doTry()
.process(new ThrowExceptionProcessor())
.doCatch(Exception.class)
.setBody(exceptionMessage())
.end();
}
};
}
@Test
public void testProcessor() throws Exception{
Assert.assertEquals("Test exception", template.requestBody("direct:withProcessor","throw"));
Assert.assertEquals("Processed OK", template.requestBody("direct:withProcessor","do not throw"));
}
@Test
public void testSimple() throws Exception{
Assert.assertEquals("Test exception", template.requestBody("direct:withSimple","throw"));
Assert.assertEquals("Processed OK", template.requestBody("direct:withSimple","do not throw"));
}
@Test
public void testValueBuilder() throws Exception{
Assert.assertEquals("Test exception", template.requestBody("direct:withValueBuilder","throw"));
Assert.assertEquals("Processed OK", template.requestBody("direct:withValueBuilder","do not throw"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment