apache-camel

Camel onexception retry failure route


I am new to camel and on exception I am calling a failureRoute and in failureRoute I am writing failed messaged to MQ. But In case of any exception in failure route like connecting to MQ I want to retry failureRoute atleast 3 times.

onException(Exception.class)
    .useOriginalMessage()
    .handled(true)
    .log(LoggingLevel.ERROR, "Exception --> ${exception.stacktrace}")
    .to("direct:failureRoute");

from("direct:failureRoute")
    .transacted()
    .routeId("failure-route")
    .to("wmqJmsTemplate:{{mq.failure.queue}}?preserveMessageQos=true")

Solution

  • You should create a redelivery policy, with number of retries set to 3.

    protected RedeliveryPolicyDefinition createRedeliveryPolicy(String maximumRedeliveries,
                                                                String redeliveryDelay) {
        RedeliveryPolicyDefinition redeliveryPolicy = new RedeliveryPolicyDefinition();
        redeliveryPolicy.setMaximumRedeliveries(maximumRedeliveries);
        redeliveryPolicy.setRedeliveryDelay(redeliveryDelay);
        redeliveryPolicy.retryAttemptedLogLevel(LoggingLevel.WARN);
        redeliveryPolicy.logRetryStackTrace(false);
        return redeliveryPolicy;
    }
    

    Where the parameter maximumRedeliveries is set to 3.

    An example would be :

    from("direct:failureRoute")
    .transacted()
    .routeId("failure-route")
    .to("wmqJmsTemplate:{{mq.failure.queue}}?preserveMessageQos=true")
    .onException(Exception.class)
        .useOriginalMessage()
        .handled(true)
        .process(this::logException)
        .onRedelivery(this::logAttemptRedelivery)
        .maximumRedeliveries(3)
        .redeliveryDelay(1000)
        .process(exchange -> {
            // Accessing and logging the original message
            Message originalMessage = exchange.getIn();
            String originalBody = originalMessage.getBody(String.class);
            LoggerFactory.getLogger("RedeliveryLogger").error("Final retry failed. Original Message: " + originalBody);
        })
        .log(LoggingLevel.ERROR, "Failed after max retry attempts. Original Message: ${body}")
        .to("log:failedMessages?level=ERROR")
        .end()
    .to("direct:failureRoute");
    

    And to configure logback :