From 8da1a4ef4086a1c2ac3ab4dd4e1d5a23d2baac95 Mon Sep 17 00:00:00 2001 From: Guillaume Nodet Date: Wed, 9 Sep 2026 06:08:36 +0000 Subject: [PATCH] CAMEL-24651: Fix NPE in ExceptionHelper.stackTraceToString() when exception is null When ${exception.stacktrace} is evaluated on an exchange that has no exception, LanguageHelper.exceptionStacktrace() calls ExceptionHelper.stackTraceToString(null), which then NPEs on e.printStackTrace(printWriter). Add a null guard in ExceptionHelper.stackTraceToString() so that it returns null when the supplied Throwable is null, consistent with the existing behaviour of LanguageHelper.exceptionMessage(). --- .../java/org/apache/camel/language/simple/SimpleTest.java | 8 ++++++++ .../java/org/apache/camel/support/ExceptionHelper.java | 5 ++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/core/camel-core/src/test/java/org/apache/camel/language/simple/SimpleTest.java b/core/camel-core/src/test/java/org/apache/camel/language/simple/SimpleTest.java index 2bb10c6cc3ac2..9e14b4bf6da3e 100644 --- a/core/camel-core/src/test/java/org/apache/camel/language/simple/SimpleTest.java +++ b/core/camel-core/src/test/java/org/apache/camel/language/simple/SimpleTest.java @@ -641,6 +641,14 @@ public void testExceptionStacktrace() { assertTrue(out.contains("at org.apache.camel.language.")); } + @Test + public void testExceptionStacktraceNoException() { + // CAMEL-24651 + String out = context.resolveLanguage("simple").createExpression("${exception.stacktrace}").evaluate(exchange, + String.class); + assertNull(out); + } + @Test public void testException() { exchange.setException(new IllegalArgumentException("Just testing")); diff --git a/core/camel-support/src/main/java/org/apache/camel/support/ExceptionHelper.java b/core/camel-support/src/main/java/org/apache/camel/support/ExceptionHelper.java index d1e6849546b90..1f37fc3a2b9dd 100644 --- a/core/camel-support/src/main/java/org/apache/camel/support/ExceptionHelper.java +++ b/core/camel-support/src/main/java/org/apache/camel/support/ExceptionHelper.java @@ -33,9 +33,12 @@ private ExceptionHelper() { * Dumps the stack trace from the given exception to a String * * @param e the exception to print the stack trace - * @return A string instance with the stack trace for the given exception + * @return A string instance with the stack trace for the given exception, or null if the exception is null */ public static String stackTraceToString(Throwable e) { + if (e == null) { + return null; + } final StringWriter writer = new StringWriter(); final PrintWriter printWriter = new PrintWriter(writer, true); e.printStackTrace(printWriter);