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 try and catch. Camel instead wraps every step of a route in an error handler, chosen once for the route, so the steps themselves stay free of error code. When a step throws, the exception is stored on the exchange, and the error handler takes over.

The error handler makes its decisions in this order:

  1. It looks for an onException clause that matches the exception, and uses that clause's settings if there is one.
  2. It retries the failed step, as often and with the delays the redelivery policy says. By default it does not retry at all.
  3. 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).
  4. Whether the caller sees the exception depends on handled: a handled failure looks like a success to the caller.
Error handling tools in Camel
ToolScopeBest for
DefaultErrorHandlerRoute builder or routeThe default: log, optionally retry, return the failure
deadLetterChannel(uri)Route builder or routeMoving failed messages aside for later inspection
onException(Class)Route builder, route configuration or routeDifferent treatment for different exceptions
doTry, doCatch, doFinallyA block of stepsLocal recovery, like Java's try
circuitBreaker()A block of stepsNot calling a service that keeps failing
noErrorHandler()Route builder or routeLeaving all handling to the caller, often a transacted consumer

The default error handler logs an exhausted failure at ERROR, with the route's message history and the full stack trace. That output contains message ids and object addresses that change on every run, so the programs on this page switch it off with logExhausted(false) and print what happened themselves. They run with Camel 4.23 on Java 21, with camel-main and the core components; the circuit breaker example adds camel-resilience4j.

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:

Java
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();
    }
}
Output
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 CamelRedelivered=true and CamelRedeliveryCounter 1 and 2. Call 3 succeeded, so the exchange completed normally, as if nothing had happened.
  • The retries came about 200 ms and 400 ms after the previous attempt: useExponentialBackOff() with backOffMultiplier(2) doubled the delay each time.
  • The body stayed order+enriched 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.
  • 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 partner busy, and the caller got the exception.

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() schedules the retry instead and frees the thread, which matters for consumers that process many messages at once.

onException: handled, continued or neither

An onException clause applies its own steps and settings to one family of exceptions. What happens after those steps depends on two flags. One route that always throws a checked InvalidOrderException is called three times, each time selecting a different clause with onWhen:

Java
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();
    }
}
Output
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
  • handled(true): the clause replaced the body with rejected: quantity must be positive 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.
  • continued(true): the exception was ignored and the route went on with the next step, so the body became order stored. Use it only for failures that really do not matter, since the route behaves as if the failing step had worked.
  • 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.

onWhen adds a condition to a clause, so several clauses can handle the same exception class in different situations; Camel tries them in the order they are declared. Clauses also take their own redelivery settings, such as onException(ConnectException.class).maximumRedeliveries(5), which override the error handler's for that exception only.

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:

Java
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();
    }
}
Output
ConnectException                                   -> matched ConnectException
FileNotFoundException (an IOException)             -> matched IOException
RuntimeCamelException wrapping ConnectException    -> matched ConnectException
IllegalArgumentException                           -> matched Exception
  • ConnectException matched its own clause, although the Exception and IOException clauses were declared first and would also match.
  • FileNotFoundException has no clause of its own. Its closest superclass with a clause is IOException, so that one matched.
  • The RuntimeCamelException wrapping a ConnectException matched the ConnectException clause. Camel walks the cause chain, starting from the innermost cause, so wrapper exceptions from components do not hide the real failure.
  • IllegalArgumentException fell back to the Exception clause, the catch-all.

Because the closest match wins, a catch-all onException(Exception.class) is safe to keep next to specific clauses. Be careful with it all the same: with handled(true) it also swallows programming errors such as NullPointerException, which then never reach your logs unless the clause logs them.

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() set:

Java
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();
    }
}
Output
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 42, the body as it entered the route, not the converted <invoice>42</invoice>. useOriginalMessage() restores the incoming message, so the dead letter can be replayed through the same route once the ledger is back.
  • For the same reason, the header stage set by the route, and the redelivery counter, are not on the dead letter.
  • The exception and the failing route are available as exchange properties: CamelExceptionCaught held ledger offline, and CamelFailureRouteId named send, the sub-route where the failure happened.
  • 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(), the dead letter holds the message as it was at the failing step, which helps debugging but may not be replayable. useOriginalBody() keeps the original body but the current headers, a middle ground.

doTry blocks and the scope of onException

Two rules decide whether a handler applies at all, and both fail silently. This program shows a doTry block in a route that has a retrying error handler, and an onException clause that reaches one route but not another:

Java
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();
    }
}
Output
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
  • doCatch caught the exception and set the body, doFinally ran, and the route continued after end(), just like a Java try statement.
  • The failing step ran once, although the route builder's error handler is set to retry twice. Inside doTry, the error handler does not apply, so there is no redelivery; use onException when you want retries.
  • The route direct:sameBuilder was handled by the onException clause, because it was defined in the same RouteBuilder.
  • The route direct:otherBuilder threw the same IllegalStateException, but it lives in another RouteBuilder, so the clause did not apply and the caller got the exception.

An onException or errorHandler call at the top of configure() applies to the routes of that builder only. To share error handling across builders, Camel has route configurations: a RouteConfigurationBuilder declares clauses once, and routes pick them up by default or by id with routeConfigurationId. A clause written inside a route, after from(...), applies to that route only.

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:

Java
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();
    }
}
Output
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, cached price 9.50. The breaker needs minimumNumberOfCalls(4) before it judges the failure rate, so it stayed CLOSED until the fourth failure.
  • After call 4, with a 100 percent failure rate, the breaker was OPEN. Calls 5 and 6 got the fallback without touching the service; the count of service calls stayed at 4.
  • After the 500 ms wait, call 7 was let through as a trial (the half-open state allows one, set by permittedNumberOfCallsInHalfOpenState(1)). It succeeded, so the breaker closed again, and call 8 went through normally.

The breaker's state is kept per circuitBreaker() block and shared by all exchanges, which is the point: one exchange's failures protect the next. Choose the fallback carefully: a cached value, a default reply or a message to a retry queue are good fallbacks, while a fallback that calls another fragile service only moves the problem. The waitDurationInOpenState(int) overload is deprecated in Camel 4.23; pass a string, as here, which is read as milliseconds.

Choosing an error handling strategy

Error handling for common failure types
FailureHandling
Temporary, such as a timeout or a busy serviceRedelivery with exponential back-off, on an onException for those exceptions
Bad data that will never succeedonException(...).handled(true) with an error reply, no retries
Messages that must not be lostdeadLetterChannel to a durable endpoint, with useOriginalMessage()
A failure that does not mattercontinued(true), sparingly
Recovery local to a few stepsdoTry / doCatch, remembering there is no redelivery inside
A service that is down for minutescircuitBreaker() with a fallback
Rules shared by many route buildersA RouteConfigurationBuilder
A transacted JMS or database consumerUsually noErrorHandler() or a transaction error handler, so the broker or database redelivers

For failures inside a split, where one bad item should not stop the batch, see the splitter page; for rejections from a throttler, see the throttler page. Every error path deserves a test, and the Camel testing page shows how to force exceptions into a route with mock endpoints and AdviceWith.