From 7680d695a6952d6c0aa26da57be767480d1235f9 Mon Sep 17 00:00:00 2001 From: Benjamin Trent <4357155+benwtrent@users.noreply.github.com> Date: Mon, 4 Aug 2025 15:34:25 -0400 Subject: [PATCH] Adjust exception wrapping logic when converting to ES exceptions --- .../org/elasticsearch/ExceptionsHelper.java | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/ExceptionsHelper.java b/server/src/main/java/org/elasticsearch/ExceptionsHelper.java index e2e61d78024f2..b1dd60cb512fd 100644 --- a/server/src/main/java/org/elasticsearch/ExceptionsHelper.java +++ b/server/src/main/java/org/elasticsearch/ExceptionsHelper.java @@ -54,8 +54,11 @@ public static RuntimeException convertToRuntime(Exception e) { } public static ElasticsearchException convertToElastic(Exception e) { - if (e instanceof ElasticsearchException) { - return (ElasticsearchException) e; + if (e instanceof ElasticsearchException ese) { + return ese; + } + if (getInnerMostCause(e) instanceof ElasticsearchException ese) { + return ese; } return new ElasticsearchException(e); } @@ -75,6 +78,24 @@ public static RestStatus status(Throwable t) { return RestStatus.INTERNAL_SERVER_ERROR; } + /** + * Unwraps while the throwable has a cause and the cause is not the same as the throwable itself. + * If you are wanting to unwrap an {@link ElasticsearchWrapperException} use {@link #unwrapCause(Throwable)} instead. + * @param t Throwable to unwrap + * @return the innermost cause of the given throwable, or the throwable itself if it has no cause + */ + private static Throwable getInnerMostCause(Throwable t) { + int counter = 0; + Throwable result = t; + while (t.getCause() != null && t.getCause() != result) { + if (counter++ > 10) { + return result; + } + result = result.getCause(); + } + return result; + } + public static Throwable unwrapCause(Throwable t) { int counter = 0; Throwable result = t;