This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new c1d1663307ea CAMEL-26980: camel-core - the error handler no longer
adds suppressed exceptions to a throwException instance (#30011)
c1d1663307ea is described below
commit c1d1663307ea4a341f3984a55f0afc7407c18056
Author: Federico Mariani <[email protected]>
AuthorDate: Sun Nov 15 16:35:24 2026 +0100
CAMEL-26980: camel-core - the error handler no longer adds suppressed
exceptions to a throwException instance (#30011)
The exception instance a throwException step is configured with is shared
by all the messages, so the error
handlers no longer add the previous exception of each message to it as
suppressed (it grew with every failure).
throwException(type, message) still creates a new exception per message,
with the previous one as suppressed.
CAMEL-26980: camel-core - doFinally, onCompletion, multicast, saga and
error handler predicates no longer add suppressed exceptions to a
throwException instance
The instances throwException steps are configured with are kept in a weak
identity set (filled in the constructor)
instead of an exchange property, so the marker follows the exception to any
exchange and nothing shows in the
exchange properties. The other paths that added an exception of each
message to the shared instance (a failing
onException predicate, doFinally, onCompletion, saga compensation,
aggregation strategy completion) skip it, and log
the other exception instead. FatalFallbackErrorHandler no longer reads a
suppressed exception of a shared instance as
the previous exception of the message.
Co-Authored-By: Claude <[email protected]>
---
.../camel/catalog/docs/throwException-eip.adoc | 19 ++
.../modules/eips/pages/throwException-eip.adoc | 19 ++
.../camel/processor/FatalFallbackErrorHandler.java | 8 +-
.../apache/camel/processor/FinallyProcessor.java | 3 +-
.../apache/camel/processor/MulticastProcessor.java | 3 +-
.../camel/processor/OnCompletionProcessor.java | 3 +-
.../camel/processor/ThrowExceptionProcessor.java | 53 ++++++
.../errorhandler/RedeliveryErrorHandler.java | 12 +-
.../apache/camel/processor/saga/SagaProcessor.java | 9 +-
.../apache/camel/processor/DoTryEdgeCasesTest.java | 4 +-
...FailOverLoadBalanceSuppressedExceptionTest.java | 12 +-
.../processor/SagaCompensationFailureTest.java | 17 ++
.../ThrowExceptionSharedInstanceTest.java | 202 +++++++++++++++++++++
.../onexception/ErrorHandlerFailurePathsTest.java | 4 +-
.../OnExceptionGlobalScopedRecursionTest.java | 12 +-
.../OnExceptionHandledThrowsExceptionTest.java | 4 +-
.../onexception/OnExceptionRecursionTest.java | 7 +-
.../OnExceptionRouteScopedRecursionTest.java | 12 +-
...xceptionRoutePolicySuppressedExceptionTest.java | 10 +-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 10 +
20 files changed, 383 insertions(+), 40 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/throwException-eip.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/throwException-eip.adoc
index cece8b1ba4a9..0ba5d7801bb6 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/throwException-eip.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/throwException-eip.adoc
@@ -106,6 +106,25 @@ In YML you specify the FQN class name via `exceptionType`
and the `message` is t
----
====
+=== Exception instance or exception type
+
+An exception instance, such as `throwException(new
IllegalArgumentException("Not allowed"))` in Java, or a bean
+referred to with `ref`, is one object that every message fails with. So that
it does not keep the exceptions of all
+the messages, the error handler and the EIPs do not add other exceptions to it
as suppressed: the previous exception of
+the message (such as the one an `onException` translates) is not added, and an
exception from a predicate of
+`onException` (such as `handled`), a `doFinally`, an `onCompletion`, a saga
compensation, or the completion of the
+aggregation strategy of a Multicast, Recipient List or Split is logged instead.
+
+To get a new exception for each message, give the exception type and the
message instead, as `exceptionType` and
+`message` do in XML and YAML. The message supports the
xref:languages:simple-language.adoc[Simple] language, and the
+new exception has the previous exception of the message as suppressed:
+
+[source,java]
+----
+onException(IOException.class)
+ .throwException(IllegalStateException.class, "Cannot process order
${header.orderId}");
+----
+
== See Also
See also the related xref:stop-eip.adoc[Stop] EIP.
diff --git
a/core/camel-core-engine/src/main/docs/modules/eips/pages/throwException-eip.adoc
b/core/camel-core-engine/src/main/docs/modules/eips/pages/throwException-eip.adoc
index cece8b1ba4a9..0ba5d7801bb6 100644
---
a/core/camel-core-engine/src/main/docs/modules/eips/pages/throwException-eip.adoc
+++
b/core/camel-core-engine/src/main/docs/modules/eips/pages/throwException-eip.adoc
@@ -106,6 +106,25 @@ In YML you specify the FQN class name via `exceptionType`
and the `message` is t
----
====
+=== Exception instance or exception type
+
+An exception instance, such as `throwException(new
IllegalArgumentException("Not allowed"))` in Java, or a bean
+referred to with `ref`, is one object that every message fails with. So that
it does not keep the exceptions of all
+the messages, the error handler and the EIPs do not add other exceptions to it
as suppressed: the previous exception of
+the message (such as the one an `onException` translates) is not added, and an
exception from a predicate of
+`onException` (such as `handled`), a `doFinally`, an `onCompletion`, a saga
compensation, or the completion of the
+aggregation strategy of a Multicast, Recipient List or Split is logged instead.
+
+To get a new exception for each message, give the exception type and the
message instead, as `exceptionType` and
+`message` do in XML and YAML. The message supports the
xref:languages:simple-language.adoc[Simple] language, and the
+new exception has the previous exception of the message as suppressed:
+
+[source,java]
+----
+onException(IOException.class)
+ .throwException(IllegalStateException.class, "Cannot process order
${header.orderId}");
+----
+
== See Also
See also the related xref:stop-eip.adoc[Stop] EIP.
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/FatalFallbackErrorHandler.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/FatalFallbackErrorHandler.java
index 25dc5ebceca8..a65b878e35b9 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/FatalFallbackErrorHandler.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/FatalFallbackErrorHandler.java
@@ -99,7 +99,10 @@ public class FatalFallbackErrorHandler extends
DelegateAsyncProcessor implements
if (previous != null && previous ==
exchange.getException()) {
previous = null;
// maybe previous was suppressed?
- if (exchange.getException().getSuppressed().length
> 0) {
+ // (not on an exception that a throwException step
shares with all the messages, whose
+ // suppressed exceptions are not of this message)
+ if
(!ThrowExceptionProcessor.isSharedException(exchange.getException())
+ &&
exchange.getException().getSuppressed().length > 0) {
previous =
exchange.getException().getSuppressed()[0];
}
}
@@ -117,7 +120,8 @@ public class FatalFallbackErrorHandler extends
DelegateAsyncProcessor implements
}
// add previous as suppressed to exception if not
already there
- if (previous != null) {
+ // (but not to an exception that a throwException step
shares with all the messages)
+ if (previous != null &&
!ThrowExceptionProcessor.isSharedException(exchange.getException())) {
Throwable[] suppressed =
exchange.getException().getSuppressed();
boolean found = false;
for (Throwable t : suppressed) {
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/FinallyProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/FinallyProcessor.java
index 7b63ffc9fb62..7b66d5db1768 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/FinallyProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/FinallyProcessor.java
@@ -172,9 +172,10 @@ public class FinallyProcessor extends
BaseDelegateProcessorSupport
}
} else {
// the original exception is kept, and an exception from
the doFinally is added as suppressed
+ // (or logged, when the original is the exception instance
of a throwException step)
Exception finallyException = exchange.getException();
if (finallyException != null && finallyException !=
exception) {
- exception.addSuppressed(finallyException);
+ ThrowExceptionProcessor.addSuppressed(exchange,
exception, finallyException);
}
// set exception back on exchange
exchange.setException(exception);
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/MulticastProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/MulticastProcessor.java
index 6dee6d71490f..26caf83e42fe 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/MulticastProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/MulticastProcessor.java
@@ -1052,7 +1052,8 @@ public class MulticastProcessor extends
BaseProcessorSupport
// no error handler has seen it yet, so it is not exhausted
(as when aggregate throws)
exhaust = false;
} else if (cause != completionFailure) {
- cause.addSuppressed(completionFailure);
+ // (or logged, when the cause is the exception instance of a
throwException step)
+ ThrowExceptionProcessor.addSuppressed(original, cause,
completionFailure);
}
exception = true;
}
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java
index 519996181c8f..0d4eecb16a34 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/OnCompletionProcessor.java
@@ -366,8 +366,9 @@ public class OnCompletionProcessor extends
BaseProcessorSupport
exchange.getExchangeExtension().setRedeliveryExhausted(exhausted);
if (cause != null) {
// if there is any exception in onCompletionProcessor, the
exception should be suppressed
+ // (or logged, when the cause is the exception instance of a
throwException step)
if (exchange.isFailed()) {
- cause.addSuppressed(exchange.getException());
+ ThrowExceptionProcessor.addSuppressed(exchange, cause,
exchange.getException());
}
exchange.setException(cause);
}
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/ThrowExceptionProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/ThrowExceptionProcessor.java
index bbc23118238b..29898d26f149 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/ThrowExceptionProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/ThrowExceptionProcessor.java
@@ -17,6 +17,9 @@
package org.apache.camel.processor;
import java.lang.reflect.Constructor;
+import java.util.Collections;
+import java.util.Set;
+import java.util.WeakHashMap;
import org.apache.camel.AsyncCallback;
import org.apache.camel.CamelContext;
@@ -29,6 +32,8 @@ import org.apache.camel.spi.IdAware;
import org.apache.camel.spi.RouteIdAware;
import org.apache.camel.spi.StepIdAware;
import org.apache.camel.util.ObjectHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The processor which sets an {@link Exception} on the {@link Exchange}
@@ -36,6 +41,16 @@ import org.apache.camel.util.ObjectHelper;
public class ThrowExceptionProcessor extends BaseProcessorSupport
implements Traceable, IdAware, RouteIdAware, StepIdAware,
CamelContextAware {
+ private static final Logger LOG =
LoggerFactory.getLogger(ThrowExceptionProcessor.class);
+
+ // The exception instances that throwException steps are configured with
(also by ref, which is looked up when the
+ // route is created): each is one object shared by all the messages. Kept
by the exception, and not on the
+ // exchange, as the exception can reach another exchange without the
properties of the one it was thrown on (such
+ // as from a copy of the exchange by the topic load balancer). Weak keys,
so an instance is not kept after its route
+ // is removed. Throwable does not override equals, so the set is by
identity.
+ private static final Set<Throwable> SHARED_EXCEPTIONS
+ = Collections.synchronizedSet(Collections.newSetFromMap(new
WeakHashMap<>()));
+
private String id;
private String routeId;
private String stepId;
@@ -53,6 +68,10 @@ public class ThrowExceptionProcessor extends
BaseProcessorSupport
this.exception = exception;
this.type = type;
this.message = message;
+ if (exception != null && (type == null || message == null)) {
+ // the instance is set on every message (see process)
+ SHARED_EXCEPTIONS.add(exception);
+ }
}
@Override
@@ -85,6 +104,40 @@ public class ThrowExceptionProcessor extends
BaseProcessorSupport
return true;
}
+ /**
+ * Whether the exception is an instance a throwException step is
configured with: one object shared by all the
+ * messages, to which Camel must not add the exceptions of a message as
suppressed (it would keep them all).
+ * <p>
+ * Internal API, for the processors of Camel.
+ *
+ * @param exception the exception
+ * @return <code>true</code> if the exception is shared by all
the messages
+ */
+ public static boolean isSharedException(Throwable exception) {
+ return exception != null && SHARED_EXCEPTIONS.contains(exception);
+ }
+
+ /**
+ * Adds the other exception as suppressed to the exception the exchange
failed with, unless that is an instance a
+ * throwException step is configured with (see {@link
#isSharedException(Throwable)}): then the other exception is
+ * logged instead.
+ * <p>
+ * Internal API, for the processors of Camel.
+ *
+ * @param exchange the exchange
+ * @param exception the exception the exchange failed with
+ * @param other the other exception, such as from a doFinally that
failed too
+ */
+ public static void addSuppressed(Exchange exchange, Throwable exception,
Throwable other) {
+ if (isSharedException(exception)) {
+ LOG.warn("Exchange: {} failed with {}, the exception instance of a
throwException step which all the messages"
+ + " share, so this other exception is logged and not
added to it as suppressed. Caused by: {}",
+ exchange.getExchangeId(), exception, other.getMessage(),
other);
+ } else {
+ exception.addSuppressed(other);
+ }
+ }
+
@Override
public String getTraceLabel() {
String className = this.exception == null ? this.type.getSimpleName()
: this.exception.getClass().getSimpleName();
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/RedeliveryErrorHandler.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/RedeliveryErrorHandler.java
index 2dc025b59bbf..570c8ae1a4fe 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/RedeliveryErrorHandler.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/errorhandler/RedeliveryErrorHandler.java
@@ -43,6 +43,7 @@ import org.apache.camel.processor.PooledExchangeTask;
import org.apache.camel.processor.PooledExchangeTaskFactory;
import org.apache.camel.processor.PooledTaskFactory;
import org.apache.camel.processor.PrototypeTaskFactory;
+import org.apache.camel.processor.ThrowExceptionProcessor;
import org.apache.camel.spi.AsyncProcessorAwaitManager;
import org.apache.camel.spi.CamelLogger;
import org.apache.camel.spi.ErrorHandlerRedeliveryCustomizer;
@@ -463,7 +464,8 @@ public abstract class RedeliveryErrorHandler extends
ErrorHandlerSupport
* Evaluates a predicate of the error handler (such as handled or
continued). A predicate that fails (throws an
* exception) is regarded as <code>false</code>, as the error handler must
still handle the exchange (such as the
* dead letter channel which always handles the exchange). The original
caused exception is kept, and the exception
- * from the predicate is logged and added as suppressed to the original
exception.
+ * from the predicate is logged and added as suppressed to the original
exception (unless that is the exception
+ * instance of a throwException step, which all the messages share).
*/
static boolean matchesPredicate(Predicate predicate, Exchange exchange,
String name) {
try {
@@ -479,7 +481,7 @@ public abstract class RedeliveryErrorHandler extends
ErrorHandlerSupport
if (original == null) {
original = exchange.getException();
}
- if (original != null && original != e) {
+ if (original != null && original != e &&
!ThrowExceptionProcessor.isSharedException(original)) {
original.addSuppressed(e);
}
LOG.warn("Error evaluating the {} predicate of the error handler on
exchange: {}. The predicate is regarded as false."
@@ -1049,9 +1051,10 @@ public abstract class RedeliveryErrorHandler extends
ErrorHandlerSupport
// the previous exception was handled (continued) so this is a
new failure
previous = null;
}
- if (previous != null && previous != e && e != null) {
+ if (previous != null && previous != e && e != null &&
!ThrowExceptionProcessor.isSharedException(e)) {
// a 2nd exception was thrown while handling a previous
exception
// so we need to add the previous as suppressed by the new
exception
+ // (but not to an exception that a throwException step shares
with all the messages)
// see also FatalFallbackErrorHandler
Throwable[] suppressed = e.getSuppressed();
boolean found = false;
@@ -1767,9 +1770,10 @@ public abstract class RedeliveryErrorHandler extends
ErrorHandlerSupport
// the previous exception was handled (continued) so this is a
new failure
previous = null;
}
- if (previous != null && previous != e) {
+ if (previous != null && previous != e &&
!ThrowExceptionProcessor.isSharedException(e)) {
// a 2nd exception was thrown while handling a previous
exception
// so we need to add the previous as suppressed by the new
exception
+ // (but not to an exception that a throwException step shares
with all the messages)
// see also FatalFallbackErrorHandler
Throwable[] suppressed = e.getSuppressed();
boolean found = false;
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/saga/SagaProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/saga/SagaProcessor.java
index d5e1d062c8f5..8d86ab61cc01 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/saga/SagaProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/saga/SagaProcessor.java
@@ -24,6 +24,7 @@ import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.Traceable;
import org.apache.camel.processor.BaseDelegateProcessorSupport;
+import org.apache.camel.processor.ThrowExceptionProcessor;
import org.apache.camel.saga.CamelSagaCoordinator;
import org.apache.camel.saga.CamelSagaService;
import org.apache.camel.saga.CamelSagaStep;
@@ -114,10 +115,10 @@ public abstract class SagaProcessor extends
BaseDelegateProcessorSupport
final Exception cause = exchange.getException();
coordinator.compensate(exchange).whenComplete((done, ex)
-> {
if (ex != null) {
- // keep the exception that caused the
compensation, and attach the compensation failure to it.
- // This adds to the exception instance thrown by
the route: if a route throws a shared
- // instance, its suppressed exceptions grow with
every failed compensation
- cause.addSuppressed(unwrap(ex));
+ // keep the exception that caused the
compensation, and attach the compensation failure to it
+ // (or log it, when the cause is the exception
instance of a throwException step, which all
+ // the messages share)
+ ThrowExceptionProcessor.addSuppressed(exchange,
cause, unwrap(ex));
exchange.setException(cause);
callback.done(false);
} else {
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/DoTryEdgeCasesTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/DoTryEdgeCasesTest.java
index f5fb53c7ba6d..36ff5a78e494 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/DoTryEdgeCasesTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/DoTryEdgeCasesTest.java
@@ -138,7 +138,9 @@ public class DoTryEdgeCasesTest extends ContextTestSupport {
public void configure() {
from("direct:start")
.doTry()
- .throwException(new IOException("original"))
+ // a new exception for each message, as an
exception instance (shared by all the
+ // messages) gets no suppressed exceptions
+ .throwException(IOException.class, "original")
.doCatch(IllegalArgumentException.class)
.to("mock:catch")
.doFinally()
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/FailOverLoadBalanceSuppressedExceptionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/FailOverLoadBalanceSuppressedExceptionTest.java
index 9236be24a982..bce1eb847de7 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/FailOverLoadBalanceSuppressedExceptionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/FailOverLoadBalanceSuppressedExceptionTest.java
@@ -39,10 +39,12 @@ class FailOverLoadBalanceSuppressedExceptionTest extends
ContextTestSupport {
return new RouteBuilder() {
@Override
public void configure() {
+ // the doTry blocks throw a new exception for each message, as
an exception instance (shared by all the
+ // messages) gets no suppressed exceptions
failover("finally");
from("direct:finally-attempt")
.doTry()
- .throwException(new IOException("original"))
+ .throwException(IOException.class, "original")
.doFinally()
.throwException(new
IllegalArgumentException("cleanup"))
.end();
@@ -50,7 +52,7 @@ class FailOverLoadBalanceSuppressedExceptionTest extends
ContextTestSupport {
failover("finallyRoute");
from("direct:finallyRoute-attempt")
.doTry()
- .throwException(new IOException("original"))
+ .throwException(IOException.class, "original")
.doFinally()
.to("direct:cleanup")
.end();
@@ -78,7 +80,7 @@ class FailOverLoadBalanceSuppressedExceptionTest extends
ContextTestSupport {
failover("monitoredFinally");
from("direct:monitoredFinally-attempt")
.doTry()
- .throwException(new
IllegalArgumentException("original"))
+ .throwException(IllegalArgumentException.class,
"original")
.doFinally()
.throwException(new IOException("cleanup"))
.end();
@@ -92,7 +94,7 @@ class FailOverLoadBalanceSuppressedExceptionTest extends
ContextTestSupport {
.onException(IllegalArgumentException.class).to("direct:audit").end()
.throwException(new
IllegalArgumentException("original"));
from("direct:audit")
- .throwException(new IOException("audit"));
+ .throwException(IOException.class, "audit");
failover("onWhenFails");
from("direct:onWhenFails-attempt")
@@ -127,7 +129,7 @@ class FailOverLoadBalanceSuppressedExceptionTest extends
ContextTestSupport {
from("direct:onException")
.onException(IllegalArgumentException.class).handled(true).to("mock:onException").end()
.doTry()
- .throwException(new IOException("original"))
+ .throwException(IOException.class, "original")
.doFinally()
.throwException(new
IllegalArgumentException("cleanup"))
.end();
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/SagaCompensationFailureTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/SagaCompensationFailureTest.java
index 49c301709787..838812886220 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/SagaCompensationFailureTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/SagaCompensationFailureTest.java
@@ -40,6 +40,7 @@ import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -54,6 +55,7 @@ public class SagaCompensationFailureTest extends
ContextTestSupport {
private final AtomicReference<CamelSagaCoordinator> coordinator = new
AtomicReference<>();
private final AtomicReference<String> manualSagaId = new
AtomicReference<>();
private final List<String> sagaServiceWarnings = new
CopyOnWriteArrayList<>();
+ private final IllegalArgumentException sharedFailure = new
IllegalArgumentException("shared failure");
@Test
public void testFailedCompensationKeepsTheOriginalException() {
@@ -72,6 +74,17 @@ public class SagaCompensationFailureTest extends
ContextTestSupport {
suppressed[0].getMessage());
}
+ @Test
+ public void testFailedCompensationOfThrowExceptionInstance() {
+ // the exception instance of a throwException step is shared by all
the messages, so the compensation failure
+ // of each message is not attached to it
+ for (int i = 0; i < 2; i++) {
+ Exchange result = template.send("direct:saga-shared-fails", e ->
e.getMessage().setBody("hello"));
+ assertSame(sharedFailure, result.getException());
+ }
+ assertEquals(0, sharedFailure.getSuppressed().length);
+ }
+
@Test
public void testFailedCompensationIsNotReportedAsCompensated() throws
Exception {
Exchange result = template.send("direct:saga-fails", e ->
e.getMessage().setBody("hello"));
@@ -146,6 +159,10 @@ public class SagaCompensationFailureTest extends
ContextTestSupport {
throw new IllegalArgumentException("business
failure");
});
+ from("direct:saga-shared-fails")
+ .saga().compensation("direct:finalization-fails")
+ .throwException(sharedFailure);
+
from("direct:saga-completion-fails")
.saga().completion("direct:finalization-fails")
.to("mock:end");
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/ThrowExceptionSharedInstanceTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/ThrowExceptionSharedInstanceTest.java
new file mode 100644
index 000000000000..197aabc3400e
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/ThrowExceptionSharedInstanceTest.java
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.processor;
+
+import java.io.IOException;
+
+import org.apache.camel.AggregationStrategy;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+
+/**
+ * The exception instance a throwException step is configured with is shared
by all the messages, so the error handlers
+ * and the EIPs must not add other exceptions of each message to it as
suppressed.
+ */
+public class ThrowExceptionSharedInstanceTest extends ContextTestSupport {
+
+ private final IllegalStateException translated = new
IllegalStateException("Translated");
+ private final IllegalStateException afterCatch = new
IllegalStateException("After catch");
+ private final IOException handledThrows = new IOException("Handled
throws");
+ private final IOException finallyThrows = new IOException("Finally
throws");
+ private final IOException onCompletionThrows = new
IOException("OnCompletion throws");
+ private final IOException multicastThrows = new IOException("Multicast
throws");
+ private final IllegalStateException onCopy = new IllegalStateException("On
copy");
+
+ @Test
+ public void testOnExceptionThrowsInstance() {
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:onException", e -> {
+ });
+ assertSame(translated, out.getException());
+ }
+ assertEquals(0, translated.getSuppressed().length);
+ }
+
+ @Test
+ public void testThrowsInstanceAfterDoCatch() {
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:afterCatch", e -> {
+ });
+ assertSame(afterCatch, out.getException());
+ }
+ assertEquals(0, afterCatch.getSuppressed().length);
+ }
+
+ @Test
+ public void testHandledPredicateThrows() {
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:handledThrows", e -> {
+ });
+ assertSame(handledThrows, out.getException());
+ }
+ assertEquals(0, handledThrows.getSuppressed().length);
+ }
+
+ @Test
+ public void testDoFinallyThrows() {
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:finallyThrows", e -> {
+ });
+ assertSame(finallyThrows, out.getException());
+ }
+ assertEquals(0, finallyThrows.getSuppressed().length);
+ }
+
+ @Test
+ public void testOnCompletionThrows() {
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:onCompletionThrows", e -> {
+ });
+ assertSame(onCompletionThrows, out.getException());
+ }
+ assertEquals(0, onCompletionThrows.getSuppressed().length);
+ }
+
+ @Test
+ public void testMulticastCompletionThrows() {
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:multicastThrows", e -> {
+ });
+ assertSame(multicastThrows, out.getException());
+ }
+ assertEquals(0, multicastThrows.getSuppressed().length);
+ }
+
+ @Test
+ public void testOnExceptionThrowsInstanceOnCopy() {
+ // the instance is thrown on a copy of the exchange (by the topic load
balancer), and then set on the exchange
+ for (int i = 0; i < 3; i++) {
+ Exchange out = template.send("direct:onCopy", e -> {
+ });
+ assertSame(onCopy, out.getException());
+ }
+ assertEquals(0, onCopy.getSuppressed().length);
+ }
+
+ @Test
+ public void testOnExceptionThrowsTypeAndMessage() {
+ Exchange first = template.send("direct:typeAndMessage", e -> {
+ });
+ Exchange second = template.send("direct:typeAndMessage", e -> {
+ });
+ assertNotSame(first.getException(), second.getException());
+ for (Exchange out : new Exchange[] { first, second }) {
+ Exception e = assertInstanceOf(IllegalStateException.class,
out.getException());
+ assertEquals("Translated", e.getMessage());
+ assertEquals(1, e.getSuppressed().length);
+ assertInstanceOf(IOException.class, e.getSuppressed()[0]);
+ }
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:onException")
+
.onException(IOException.class).throwException(translated).end()
+ .throwException(IOException.class, "Failure of
${exchangeId}");
+
+ from("direct:afterCatch")
+ .doTry()
+ .throwException(IOException.class, "Failure of
${exchangeId}")
+ .doCatch(IOException.class)
+ .to("mock:catch")
+ .end()
+ .throwException(afterCatch);
+
+ from("direct:typeAndMessage")
+
.onException(IOException.class).throwException(IllegalStateException.class,
"Translated").end()
+ .throwException(IOException.class, "Failure of
${exchangeId}");
+
+ from("direct:handledThrows")
+ .onException(IOException.class).handled(e -> {
+ throw new IllegalArgumentException("Handled failed
of " + e.getExchangeId());
+ }).end()
+ .throwException(handledThrows);
+
+ from("direct:finallyThrows")
+ .doTry()
+ .throwException(finallyThrows)
+ .doFinally()
+ .throwException(IllegalStateException.class,
"Finally failed of ${exchangeId}")
+ .end();
+
+ from("direct:onCompletionThrows")
+ .onCompletion().onFailureOnly().modeBeforeConsumer()
+ .throwException(IllegalStateException.class,
"OnCompletion failed of ${exchangeId}")
+ .end()
+ .throwException(onCompletionThrows);
+
+ from("direct:multicastThrows")
+ .multicast(new FailingOnCompletion())
+ .to("direct:multicastBranch")
+ .end();
+ from("direct:multicastBranch")
+ .throwException(multicastThrows);
+
+ from("direct:onCopy")
+
.onException(IOException.class).to("direct:topic").end()
+ .throwException(IOException.class, "Failure of
${exchangeId}");
+ from("direct:topic").errorHandler(noErrorHandler())
+ .loadBalance().topic().to("direct:onCopyBranch");
+ from("direct:onCopyBranch")
+ .throwException(onCopy);
+ }
+ };
+ }
+
+ private static final class FailingOnCompletion implements
AggregationStrategy {
+
+ @Override
+ public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
+ return oldExchange != null ? oldExchange : newExchange;
+ }
+
+ @Override
+ public void onCompletion(Exchange exchange, Exchange inputExchange) {
+ throw new IllegalStateException("Completion failed of " +
inputExchange.getExchangeId());
+ }
+ }
+}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/ErrorHandlerFailurePathsTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/ErrorHandlerFailurePathsTest.java
index 8ea0d86e69d5..92692c42122a 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/ErrorHandlerFailurePathsTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/ErrorHandlerFailurePathsTest.java
@@ -69,7 +69,9 @@ public class ErrorHandlerFailurePathsTest extends
ContextTestSupport {
throw new IllegalArgumentException("retryWhile failed");
});
- from("direct:start").throwException(new IOException("Forced"));
+ // a new exception for each message, as an exception instance
(shared by all the messages) gets no
+ // suppressed exceptions
+ from("direct:start").throwException(IOException.class,
"Forced");
}
});
context.start();
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionGlobalScopedRecursionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionGlobalScopedRecursionTest.java
index 7236bafc349a..b39926da3a93 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionGlobalScopedRecursionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionGlobalScopedRecursionTest.java
@@ -44,7 +44,7 @@ public class OnExceptionGlobalScopedRecursionTest extends
ContextTestSupport {
@Override
public void configure() {
onException(Throwable.class).to("mock:c").log("onException")
- .throwException(new NullPointerException("A NPE error
here")).end();
+ .throwException(NullPointerException.class, "A NPE
error here").end();
from("direct:test").to("mock:a").log("test").throwException(new
IllegalStateException("Bad state"))
.to("log:test").to("mock:b");
@@ -74,7 +74,7 @@ public class OnExceptionGlobalScopedRecursionTest extends
ContextTestSupport {
@Override
public void configure() {
onException(Throwable.class).handled(true).to("mock:c").log("onException")
- .throwException(new NullPointerException("A NPE error
here")).end();
+ .throwException(NullPointerException.class, "A NPE
error here").end();
from("direct:test").to("mock:a").log("test").throwException(new
IllegalStateException("Bad state"))
.to("log:test").to("mock:b");
@@ -112,7 +112,7 @@ public class OnExceptionGlobalScopedRecursionTest extends
ContextTestSupport {
// need to turn off error handler when linked with direct, in
// case you want the same as inlined
from("direct:error").errorHandler(noErrorHandler()).to("mock:d").log("error")
- .throwException(new NullPointerException("A NPE error
here"));
+ .throwException(NullPointerException.class, "A NPE
error here");
}
});
context.start();
@@ -147,7 +147,7 @@ public class OnExceptionGlobalScopedRecursionTest extends
ContextTestSupport {
// need to turn off error handler when linked with direct, in
// case you want the same as inlined
from("direct:error").errorHandler(noErrorHandler()).to("mock:d").log("error")
- .throwException(new NullPointerException("A NPE error
here"));
+ .throwException(NullPointerException.class, "A NPE
error here");
}
});
context.start();
@@ -179,7 +179,7 @@ public class OnExceptionGlobalScopedRecursionTest extends
ContextTestSupport {
from("direct:test").to("mock:a").log("test").throwException(new
IllegalStateException("Bad state"))
.to("log:test").to("mock:b");
-
from("direct:error").to("mock:d").log("error").throwException(new
NullPointerException("A NPE error here"));
+
from("direct:error").to("mock:d").log("error").throwException(NullPointerException.class,
"A NPE error here");
}
});
context.start();
@@ -209,7 +209,7 @@ public class OnExceptionGlobalScopedRecursionTest extends
ContextTestSupport {
from("direct:test").to("mock:a").log("test").throwException(new
IllegalStateException("Bad state"))
.to("log:test").to("mock:b");
-
from("direct:error").to("mock:d").log("error").throwException(new
NullPointerException("A NPE error here"));
+
from("direct:error").to("mock:d").log("error").throwException(NullPointerException.class,
"A NPE error here");
}
});
context.start();
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionHandledThrowsExceptionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionHandledThrowsExceptionTest.java
index 3f0e0b832fe5..ff2c5f0b7b78 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionHandledThrowsExceptionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionHandledThrowsExceptionTest.java
@@ -57,7 +57,9 @@ public class OnExceptionHandledThrowsExceptionTest extends
ContextTestSupport {
throw new IllegalArgumentException("Another
Forced");
}).to("log:foo?showAll=true").to("mock:handled");
- from("direct:start").throwException(new IOException("Forced"));
+ // a new exception for each message, as an exception instance
(shared by all the messages) gets no
+ // suppressed exceptions
+ from("direct:start").throwException(IOException.class,
"Forced");
}
};
}
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRecursionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRecursionTest.java
index e4ad0dee2895..ed0376fe41ac 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRecursionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRecursionTest.java
@@ -63,8 +63,9 @@ public class OnExceptionRecursionTest extends
ContextTestSupport {
NullPointerException npe =
assertIsInstanceOf(NullPointerException.class, e.getCause());
assertEquals("A NPE error here", npe.getMessage());
- IllegalStateException ise =
assertIsInstanceOf(IllegalStateException.class, npe.getSuppressed()[0]);
- assertEquals("Bad state", ise.getMessage());
+ // the NPE is the instance the throwException step is configured
with, which all the messages share,
+ // so the error handler does not add the ISE to it as suppressed
+ assertEquals(0, npe.getSuppressed().length);
}
assertMockEndpointsSatisfied();
@@ -80,7 +81,7 @@ public class OnExceptionRecursionTest extends
ContextTestSupport {
from("direct:test").to("mock:a").throwException(new
IllegalStateException("Bad state")).to("mock:b");
from("direct:handle").errorHandler(noErrorHandler()).to("mock:d").log("Handling
exception")
- .throwException(new NullPointerException("A NPE error
here"));
+ .throwException(NullPointerException.class, "A NPE
error here");
}
});
context.start();
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRouteScopedRecursionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRouteScopedRecursionTest.java
index 4691061cfeff..08f757005a18 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRouteScopedRecursionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/onexception/OnExceptionRouteScopedRecursionTest.java
@@ -45,7 +45,7 @@ public class OnExceptionRouteScopedRecursionTest extends
ContextTestSupport {
@Override
public void configure() {
from("direct:test").onException(Throwable.class).to("mock:c").log("onException")
- .throwException(new NullPointerException("A NPE error
here")).end().to("mock:a")
+ .throwException(NullPointerException.class, "A NPE
error here").end().to("mock:a")
.log("test").throwException(new
IllegalStateException("Bad state")).to("log:test").to("mock:b");
}
});
@@ -74,7 +74,7 @@ public class OnExceptionRouteScopedRecursionTest extends
ContextTestSupport {
@Override
public void configure() {
from("direct:test").onException(Throwable.class).handled(true).log("onException")
- .throwException(new NullPointerException("A NPE error
here")).end().to("mock:a")
+ .throwException(NullPointerException.class, "A NPE
error here").end().to("mock:a")
.log("test").throwException(new
IllegalStateException("Bad state")).to("log:test").to("mock:b");
}
});
@@ -109,7 +109,7 @@ public class OnExceptionRouteScopedRecursionTest extends
ContextTestSupport {
// need to turn off error handler when linked with direct, in
// case you want the same as inlined
from("direct:error").errorHandler(noErrorHandler()).to("mock:d").log("error")
- .throwException(new NullPointerException("A NPE error
here"));
+ .throwException(NullPointerException.class, "A NPE
error here");
}
});
context.start();
@@ -143,7 +143,7 @@ public class OnExceptionRouteScopedRecursionTest extends
ContextTestSupport {
// need to turn off error handler when linked with direct, in
// case you want the same as inlined
from("direct:error").errorHandler(noErrorHandler()).to("mock:d").log("error")
- .throwException(new NullPointerException("A NPE error
here"));
+ .throwException(NullPointerException.class, "A NPE
error here");
}
});
context.start();
@@ -174,7 +174,7 @@ public class OnExceptionRouteScopedRecursionTest extends
ContextTestSupport {
.to("mock:a").log("test")
.throwException(new IllegalStateException("Bad
state")).to("log:test").to("mock:b");
-
from("direct:error").to("mock:d").log("error").throwException(new
NullPointerException("A NPE error here"));
+
from("direct:error").to("mock:d").log("error").throwException(NullPointerException.class,
"A NPE error here");
}
});
context.start();
@@ -203,7 +203,7 @@ public class OnExceptionRouteScopedRecursionTest extends
ContextTestSupport {
.to("direct:error").end().to("mock:a").log("test")
.throwException(new IllegalStateException("Bad
state")).to("log:test").to("mock:b");
-
from("direct:error").to("mock:d").log("error").throwException(new
NullPointerException("A NPE error here"));
+
from("direct:error").to("mock:d").log("error").throwException(NullPointerException.class,
"A NPE error here");
}
});
context.start();
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingExceptionRoutePolicySuppressedExceptionTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingExceptionRoutePolicySuppressedExceptionTest.java
index 993c65e2cc8b..3b67b5069e33 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingExceptionRoutePolicySuppressedExceptionTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/throttle/ThrottlingExceptionRoutePolicySuppressedExceptionTest.java
@@ -151,16 +151,18 @@ class
ThrottlingExceptionRoutePolicySuppressedExceptionTest extends ContextTestS
return new RouteBuilder() {
@Override
public void configure() {
+ // the doTry blocks throw a new exception for each message, as
an exception instance (shared by all the
+ // messages) gets no suppressed exceptions
from("direct:finally").routePolicy(finallyPolicy)
.doTry()
- .throwException(new IllegalStateException("try"))
+ .throwException(IllegalStateException.class, "try")
.doFinally()
.throwException(new IOException("finally"))
.end();
from("direct:onException").routePolicy(onExceptionPolicy)
.onException(IOException.class).handled(true)
- .throwException(new
IllegalStateException("onException"))
+ .throwException(IllegalStateException.class,
"onException")
.end()
.throwException(new IOException("route"));
@@ -189,14 +191,14 @@ class
ThrottlingExceptionRoutePolicySuppressedExceptionTest extends ContextTestS
from("direct:listedInTry").routePolicy(listedInTryPolicy)
.doTry()
- .throwException(new IOException("try"))
+ .throwException(IOException.class, "try")
.doFinally()
.throwException(new
IllegalStateException("finally"))
.end();
from("direct:all").routePolicy(allPolicy)
.doTry()
- .throwException(new IllegalStateException("try"))
+ .throwException(IllegalStateException.class, "try")
.doFinally()
.throwException(new IOException("finally"))
.end();
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 813b37ca6542..13f59bb2b416 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -57,6 +57,16 @@ Starting in 4.24:
* The Cache EIP stores keys directly without a namespace prefix, preserving
documented cache invalidation recipes (`cache.delete(key)` and
`cache.clear()`). Note that because cache keys are un-prefixed, calling
`clear()` on a `KeyValueRepository` shared with the Cache EIP will clear all
entries in that repository, including state-store entries. It is recommended to
use a dedicated repository for the Cache EIP when co-located with state-store.
* `KeyValueAggregationRepository` safely verifies entry types before
unmarshalling, ignoring unexpected types gracefully instead of failing with a
class cast exception.
+=== camel-core - throwException with an exception instance gets no suppressed
exceptions
+
+A `throwException` step given an exception instance (`throwException(new
MyException("..."))` in Java, or a bean with
+`ref`) sets that one object on every message. The error handler no longer adds
the previous exception of the message
+(such as the one an `onException` translates) to it as suppressed: the
instance used to keep the exceptions of all the
+messages, and grew with each one. An exception from a predicate of
`onException` (such as `handled`), a `doFinally`, an
+`onCompletion`, a saga compensation, or the completion of the aggregation
strategy of a Multicast, Recipient List or
+Split is no longer added to it either, and is logged instead. Use
`throwException(MyException.class, "...")`, or
+`exceptionType` and `message`, to get a new exception for each message, with
the previous exception as suppressed.
+
=== camel-core-model - doTry keeps doCatch and doFinally in its outputs
`doCatch` and `doFinally` written as properties of `doTry` in the YAML DSL are
now kept in the outputs of the