Skip to content

Adjust exception wrapping logic when converting to ES exceptions #132419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 23 additions & 2 deletions server/src/main/java/org/elasticsearch/ExceptionsHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand All @@ -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;
Expand Down