Camel error handling: retries, handlers and dead letters
When a step in a Camel route throws, an error handler decides what happens next: try again, run an onException clause, move the message to a dead letter endpoint, or give the failure back to the caller. This page explains how that machinery decides, then runs each option with Camel 4.23, from redelivery with back-off to a circuit breaker, including the scope rules that make handlers silently not apply.
Contents
How Camel handles a failure
In a route, every step can fail: a remote call times out, a message has bad data, a database is down. Plain Java code would wrap each call in trycatch
The error handler makes its decisions in this order:
- It looks for an
clause that matches the exception, and uses that clause's settings if there is one.onException - It retries the failed step, as often and with the delays the redelivery policy says. By default it does not retry at all.
- When the retries are exhausted, it either hands the failure back to the consumer (the default error handler) or moves the message to a dead letter endpoint (the dead letter channel).
- Whether the caller sees the exception depends on
: a handled failure looks like a success to the caller.handled
| Tool | Scope | Best for |
|---|---|---|
DefaultErrorHandler | Route builder or route | The default: log, optionally retry, return the failure |
deadLetterChannel(uri) | Route builder or route | Moving failed messages aside for later inspection |
onException(Class) | Route builder, route configuration or route | Different treatment for different exceptions |
doTrydoCatchdoFinally | A block of steps | Local recovery, like Java's try |
circuitBreaker() | A block of steps | Not calling a service that keeps failing |
noErrorHandler() | Route builder or route | Leaving all handling to the caller, often a transacted consumer |
The default error handler logs an exhausted failure at ERRORlogExhausted(false)
Redelivery with exponential back-off
Many failures are temporary, such as a partner API that is briefly overloaded. A route that enriches an order and then calls such a partner is configured to retry three times, starting with a 200 ms delay that doubles each time. The partner fails twice in the first run and five times in the second:
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class Redelivery {
static final AtomicInteger CALLS = new AtomicInteger();
static long lastCall;
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false)
.maximumRedeliveries(3).redeliveryDelay(200)
.useExponentialBackOff().backOffMultiplier(2));
from("direct:flaky")
.process(e -> e.getMessage().setBody(e.getMessage().getBody(String.class)
+ "+enriched"))
.process(Redelivery::callPartner);
}
}
static void callPartner(Exchange e) {
long now = System.nanoTime();
int call = CALLS.incrementAndGet();
long gap = call == 1 ? 0 : Math.round((now - lastCall) / 1000000 / 100.0) * 100;
lastCall = now;
System.out.printf(" call %d: body=%s redelivered=%s counter=%s, "
+ "about %d ms after the last%n",
call, e.getMessage().getBody(),
e.getMessage().getHeader(Exchange.REDELIVERED),
e.getMessage().getHeader(Exchange.REDELIVERY_COUNTER), gap);
if (call < e.getMessage().getHeader("failTimes", Integer.class) + 1) {
throw new IllegalStateException("partner busy");
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("partner fails twice:");
Exchange ok = template.send("direct:flaky", e -> {
e.getMessage().setBody("order");
e.getMessage().setHeader("failTimes", 2);
});
System.out.println(" failed=" + ok.isFailed() + ", body=" + ok.getMessage().getBody());
CALLS.set(0);
System.out.println("partner fails five times:");
Exchange failed = template.send("direct:flaky", e -> {
e.getMessage().setBody("order");
e.getMessage().setHeader("failTimes", 5);
});
System.out.println(" failed=" + failed.isFailed() + ", exception="
+ failed.getException().getMessage());
camel.stop();
}
}
partner fails twice:
call 1: body=order+enriched redelivered=null counter=null, about 0 ms after the last
call 2: body=order+enriched redelivered=true counter=1, about 200 ms after the last
call 3: body=order+enriched redelivered=true counter=2, about 400 ms after the last
failed=false, body=order+enriched
partner fails five times:
call 1: body=order+enriched redelivered=null counter=null, about 0 ms after the last
call 2: body=order+enriched redelivered=true counter=1, about 200 ms after the last
call 3: body=order+enriched redelivered=true counter=2, about 400 ms after the last
call 4: body=order+enriched redelivered=true counter=3, about 800 ms after the last
failed=true, exception=partner busy
- In the first run, calls 2 and 3 were retries, marked with the headers
andCamelRedelivered=true 1 and 2. Call 3 succeeded, so the exchange completed normally, as if nothing had happened.CamelRedeliveryCounter - The retries came about 200 ms and 400 ms after the previous attempt:
withuseExponentialBackOff() doubled the delay each time.backOffMultiplier(2) - The body stayed
on every attempt. Redelivery repeats only the step that failed, with the exchange as it was just before that step, so the enrichment ran once, not four times.order+enriched - In the second run, the fourth call, the third retry, waited about 800 ms, and failed again. The retries were exhausted, so the exchange failed with
, and the caller got the exception.partner busy
The redelivery defaults are no retries, a 1000 ms delay, a multiplier of 2 and a maximum delay of 60 s. Retry only failures that can succeed later, such as timeouts and connection errors; retrying a validation error only delays its failure. By default the thread waits during the delay; asyncDelayedRedelivery()
onException: handled, continued or neither
An onExceptionInvalidOrderExceptiononWhen
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class OnExceptionModes {
static class InvalidOrderException extends Exception {
InvalidOrderException(String message) {
super(message);
}
}
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
onException(InvalidOrderException.class)
.onWhen(header("mode").isEqualTo("handled"))
.handled(true)
.setBody(simple("rejected: ${exception.message}"));
onException(InvalidOrderException.class)
.onWhen(header("mode").isEqualTo("continued"))
.continued(true);
onException(InvalidOrderException.class)
.process(e -> System.out.println(" onException ran, exception kept"));
from("direct:order")
.process(e -> {
throw new InvalidOrderException("quantity must be positive");
})
.setBody(constant("order stored"));
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
for (String mode : new String[] {"handled", "continued", "neither"}) {
System.out.println(mode + ":");
Exchange result = template.send("direct:order", e -> {
e.getMessage().setBody("order");
e.getMessage().setHeader("mode", mode);
});
System.out.println(" failed=" + result.isFailed() + ", body="
+ result.getMessage().getBody());
if (result.getException() != null) {
System.out.println(" exception: " + result.getException().getMessage());
}
}
camel.stop();
}
}
handled:
failed=false, body=rejected: quantity must be positive
continued:
failed=false, body=order stored
neither:
onException ran, exception kept
failed=true, body=order
exception: quantity must be positive
: the clause replaced the body withhandled(true) and the exchange did not fail. The route stopped at the failing step; the steps after it did not run. This is how a route returns an error reply, such as an HTTP 400 body, instead of an exception.rejected: quantity must be positive : the exception was ignored and the route went on with the next step, so the body becamecontinued(true) . Use it only for failures that really do not matter, since the route behaves as if the failing step had worked.order stored- Neither: the clause's steps ran, but the exchange still failed and the caller got the exception. That suits clauses that record or alert and leave the failure in place.
onWhenonException(ConnectException.class).maximumRedeliveries(5)
Which onException clause matches
With several clauses, Camel picks the closest match by class hierarchy, not the first in the file. The clauses here are declared from the most general to the most specific, and four different exceptions are thrown, one of them wrapped in another:
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.ConnectException;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class ExceptionMatching {
static class Routes extends RouteBuilder {
@Override
public void configure() {
onException(Exception.class).handled(true)
.setBody(constant("matched Exception"));
onException(IOException.class).handled(true)
.setBody(constant("matched IOException"));
onException(ConnectException.class).handled(true)
.setBody(constant("matched ConnectException"));
from("direct:call")
.process(e -> {
throw switch (e.getMessage().getBody(String.class)) {
case "connect" -> new ConnectException("refused");
case "file" -> new FileNotFoundException("missing.csv");
case "wrapped" -> new RuntimeCamelException(
new ConnectException("refused"));
default -> new IllegalArgumentException("bad input");
};
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
String[][] cases = {
{"connect", "ConnectException"},
{"file", "FileNotFoundException (an IOException)"},
{"wrapped", "RuntimeCamelException wrapping ConnectException"},
{"other", "IllegalArgumentException"},
};
for (String[] c : cases) {
System.out.printf("%-50s -> %s%n", c[1], template.requestBody("direct:call", c[0]));
}
camel.stop();
}
}
ConnectException -> matched ConnectException
FileNotFoundException (an IOException) -> matched IOException
RuntimeCamelException wrapping ConnectException -> matched ConnectException
IllegalArgumentException -> matched Exception
matched its own clause, although theConnectException andException clauses were declared first and would also match.IOException has no clause of its own. Its closest superclass with a clause isFileNotFoundException , so that one matched.IOException- The
wrapping aRuntimeCamelException matched theConnectException clause. Camel walks the cause chain, starting from the innermost cause, so wrapper exceptions from components do not hide the real failure.ConnectException fell back to theIllegalArgumentException clause, the catch-all.Exception
Because the closest match wins, a catch-all onException(Exception.class)handled(true)NullPointerException
Dead letter channel
A dead letter channel moves messages that still fail after their retries to another endpoint, so that one bad message does not block the rest and can be looked at later. This route converts an invoice to XML, sets a header, then calls a ledger that is offline, with useOriginalMessage()
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class DeadLetter {
static class Routes extends RouteBuilder {
@Override
public void configure() {
errorHandler(deadLetterChannel("direct:dlq")
.useOriginalMessage().maximumRedeliveries(2).redeliveryDelay(50)
.logExhausted(false));
from("direct:invoices").routeId("invoices")
.setBody(simple("<invoice>${body}</invoice>"))
.setHeader("stage", constant("converted"))
.to("direct:send");
from("direct:send").routeId("send")
.process(e -> {
throw new IllegalStateException("ledger offline");
});
from("direct:dlq").routeId("dlq")
.process(e -> {
Exception cause = e.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
System.out.println(" dead letter body : " + e.getMessage().getBody());
System.out.println(" header stage : " + e.getMessage()
.getHeader("stage"));
System.out.println(" exception caught : " + cause.getMessage());
System.out.println(" failed in route : "
+ e.getProperty(Exchange.FAILURE_ROUTE_ID));
System.out.println(" redelivery counter : "
+ e.getMessage().getHeader(Exchange.REDELIVERY_COUNTER));
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
Exchange result = template.send("direct:invoices", e -> e.getMessage().setBody("42"));
System.out.println("caller: failed=" + result.isFailed() + ", exception="
+ result.getException());
System.out.println("caller: body=" + result.getMessage().getBody());
camel.stop();
}
}
dead letter body : 42
header stage : null
exception caught : ledger offline
failed in route : send
redelivery counter : null
caller: failed=false, exception=null
caller: body=42
- The dead letter endpoint received
, the body as it entered the route, not the converted42 .<invoice>42</invoice> restores the incoming message, so the dead letter can be replayed through the same route once the ledger is back.useOriginalMessage() - For the same reason, the header
set by the route, and the redelivery counter, are not on the dead letter.stage - The exception and the failing route are available as exchange properties:
heldCamelExceptionCaught , andledger offline namedCamelFailureRouteId , the sub-route where the failure happened.send - The caller saw no failure: the dead letter channel marks the exception as handled by default, so for the caller, sending the message to the dead letter endpoint counts as success.
In production the dead letter endpoint is a durable queue, a database table or a directory, not an in-memory route, so that dead letters survive a restart. Without useOriginalMessage()useOriginalBody()
doTry blocks and the scope of onException
Two rules decide whether a handler applies at all, and both fail silently. This program shows a doTryonException
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class DoTryScopes {
static final AtomicInteger ATTEMPTS = new AtomicInteger();
static class OrderRoutes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().maximumRedeliveries(2).redeliveryDelay(0));
onException(IllegalStateException.class).handled(true)
.setBody(constant("handled by OrderRoutes onException"));
from("direct:tryCatch")
.doTry()
.process(e -> {
ATTEMPTS.incrementAndGet();
throw new IllegalArgumentException("bad price");
})
.doCatch(IllegalArgumentException.class)
.setBody(simple("caught: ${exception.message}"))
.doFinally()
.process(e -> System.out.println(" finally ran"))
.end()
.setBody(simple("${body}, route continued"));
from("direct:sameBuilder")
.process(e -> {
throw new IllegalStateException("stock service down");
});
}
}
static class OtherRoutes extends RouteBuilder {
@Override
public void configure() {
errorHandler(defaultErrorHandler().logExhausted(false));
from("direct:otherBuilder")
.process(e -> {
throw new IllegalStateException("stock service down");
});
}
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new OrderRoutes());
camel.addRoutes(new OtherRoutes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
System.out.println("doTry: " + template.requestBody("direct:tryCatch", "x")
+ " (attempts: " + ATTEMPTS.get() + ")");
System.out.println("route in the same RouteBuilder: "
+ template.requestBody("direct:sameBuilder", "x"));
try {
template.requestBody("direct:otherBuilder", "x");
} catch (Exception e) {
System.out.println("route in another RouteBuilder: not handled, "
+ e.getCause().getClass().getSimpleName());
}
camel.stop();
}
}
finally ran
doTry: caught: bad price, route continued (attempts: 1)
route in the same RouteBuilder: handled by OrderRoutes onException
route in another RouteBuilder: not handled, IllegalStateException
caught the exception and set the body,doCatch ran, and the route continued afterdoFinally , just like a Javaend() statement.try- The failing step ran once, although the route builder's error handler is set to retry twice. Inside
, the error handler does not apply, so there is no redelivery; usedoTry when you want retries.onException - The route
was handled by thedirect:sameBuilder clause, because it was defined in the sameonException .RouteBuilder - The route
threw the samedirect:otherBuilder , but it lives in anotherIllegalStateException , so the clause did not apply and the caller got the exception.RouteBuilder
An onExceptionerrorHandlerconfigure()RouteConfigurationBuilderrouteConfigurationIdfrom(...)
Circuit breaker
Retries help with short glitches but make a real outage worse: every message waits through all its retries against a service that is down. A circuit breaker counts failures and, past a threshold, stops calling the service for a while, using a fallback instead. This one, from camel-resilience4j, opens when half of the last four calls failed, and stays open for 500 ms:
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangePropertyKey;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
public class CircuitBreakerDemo {
static final AtomicInteger SERVICE_CALLS = new AtomicInteger();
static volatile boolean serviceUp = false;
static class Routes extends RouteBuilder {
@Override
public void configure() {
from("direct:price")
.circuitBreaker()
.resilience4jConfiguration()
.slidingWindowSize(4).minimumNumberOfCalls(4)
.failureRateThreshold(50).waitDurationInOpenState("500")
.permittedNumberOfCallsInHalfOpenState(1)
.end()
.process(e -> {
SERVICE_CALLS.incrementAndGet();
if (!serviceUp) {
throw new IllegalStateException("pricing service down");
}
e.getMessage().setBody("price 9.99");
})
.onFallback()
.setBody(constant("cached price 9.50"))
.end();
}
}
static void call(ProducerTemplate template, int n) {
Exchange result = template.send("direct:price", e -> e.getMessage().setBody("book"));
System.out.printf("call %d: %-18s state=%-7s service calls so far=%d%n", n,
result.getMessage().getBody(),
result.getProperty(ExchangePropertyKey.CIRCUIT_BREAKER_RESPONSE_STATE),
SERVICE_CALLS.get());
}
public static void main(String[] args) throws Exception {
CamelContext camel = new DefaultCamelContext();
camel.addRoutes(new Routes());
camel.start();
ProducerTemplate template = camel.createProducerTemplate();
for (int i = 1; i <= 6; i++) {
call(template, i);
}
System.out.println("service is back up; waiting for the open state to end");
serviceUp = true;
Thread.sleep(700);
for (int i = 7; i <= 8; i++) {
call(template, i);
}
camel.stop();
}
}
call 1: cached price 9.50 state=CLOSED service calls so far=1
call 2: cached price 9.50 state=CLOSED service calls so far=2
call 3: cached price 9.50 state=CLOSED service calls so far=3
call 4: cached price 9.50 state=OPEN service calls so far=4
call 5: cached price 9.50 state=OPEN service calls so far=4
call 6: cached price 9.50 state=OPEN service calls so far=4
service is back up; waiting for the open state to end
call 7: price 9.99 state=CLOSED service calls so far=5
call 8: price 9.99 state=CLOSED service calls so far=6
- Calls 1 to 4 reached the pricing service, failed, and returned the fallback,
. The breaker needscached price 9.50 before it judges the failure rate, so it stayedminimumNumberOfCalls(4) until the fourth failure.CLOSED - After call 4, with a 100 percent failure rate, the breaker was
. Calls 5 and 6 got the fallback without touching the service; the count of service calls stayed at 4.OPEN - After the 500 ms wait, call 7 was let through as a trial (the half-open state allows one, set by
). It succeeded, so the breaker closed again, and call 8 went through normally.permittedNumberOfCallsInHalfOpenState(1)
The breaker's state is kept per circuitBreaker()waitDurationInOpenState(int)
Choosing an error handling strategy
| Failure | Handling |
|---|---|
| Temporary, such as a timeout or a busy service | Redelivery with exponential back-off, on an onException |
| Bad data that will never succeed | onException(...).handled(true) |
| Messages that must not be lost | deadLetterChanneluseOriginalMessage() |
| A failure that does not matter | continued(true) |
| Recovery local to a few steps | doTrydoCatch |
| A service that is down for minutes | circuitBreaker() |
| Rules shared by many route builders | A RouteConfigurationBuilder |
| A transacted JMS or database consumer | Usually noErrorHandler() |
For failures inside a split, where one bad item should not stop the batch, see the AdviceWith