onException leads to infinite loop during route

Viewed 68

I have this onException block before my route

onException(Exception.class)
        .process(new IncProcessor(IncService))
        .handled(true);

What the processor does is grab the exception that occurs and uses an API to send and store it where I want it. The problem is that when that IncProcessor experiences an error, it results in an infinite loop since the onException block catches the error that occurs in IncProcessor and tries to run that same processor again. Is there any way to get around that?

1 Answers

You can wrap your error processing logic in a usual try/catch block avoiding IncProcessor errors to clutter your route business errors:

public class IncProcessor implements Processor {

    public void process(Exchange exchange) {
        try {
            // process the exchange error
        } catch (Exception e) {
            // swallow, log, or process the exception somehow
        }
    }
}

One neat way of handling this, avoiding to throw away the Exception-Processor errors, would be to

Define a new sub-Exception:

public class IncProcessingException extends RuntimeException {
    // ...
}

Wrap the error in a well-defined one:

public class IncProcessor implements Processor {

    public void process(Exchange exchange) {
        try {
            // process the exchange error
        } catch (Exception e) {
            throw new IncProcessingException(e);
        }
    }
}

Define a custom redelivery policy for the processing exception:

onException(IncProcessingException.class)
    .maximumRedeliveries(1);
Related