2222import co .elastic .clients .transport .http .TransportHttpClient ;
2323
2424import javax .annotation .Nullable ;
25+ import java .util .Objects ;
2526
2627/**
2728 * Exception thrown by API client methods when Elasticsearch could not accept or
@@ -40,12 +41,37 @@ public class ElasticsearchException extends RuntimeException {
4041
4142 public ElasticsearchException (String endpointId , ErrorResponse response ,
4243 @ Nullable TransportHttpClient .Response httpResponse ) {
43- super ("[" + endpointId + "] failed: [" + response . error (). type () + "] " + response . error (). reason ( ));
44+ super (buildCompleteErrorMessage ( endpointId , response ));
4445 this .response = response ;
4546 this .endpointId = endpointId ;
4647 this .httpResponse = httpResponse ;
4748 }
4849
50+ private static String buildCompleteErrorMessage (String endpointId , ErrorResponse response ) {
51+ ErrorCause error = response .error ();
52+ StringBuilder message = new StringBuilder ();
53+ message .append ("[" ).append (endpointId ).append ("] failed: [" ).append (error .type ()).append ("] " )
54+ .append (error .reason ());
55+
56+ // Nested errors
57+ for (ErrorCause cause = error .causedBy (); cause != null ; cause = cause .causedBy ()) {
58+ message .append ("; caused by: [" ).append (cause .type ()).append ("] " ).append (cause .reason ());
59+ }
60+
61+ // Root causes carry the actual error for generic errors such "all shards failed"
62+ for (ErrorCause rootCause : error .rootCause ()) {
63+ // Avoid repeating same message
64+ if (Objects .equals (rootCause .type (), error .type ()) && Objects .equals (rootCause .reason (), error .reason ())) {
65+ continue ;
66+ }
67+ message .append ("; root cause: [" ).append (rootCause .type ()).append ("] " ).append (rootCause .reason ());
68+ for (ErrorCause cause = rootCause .causedBy (); cause != null ; cause = cause .causedBy ()) {
69+ message .append ("; caused by: [" ).append (cause .type ()).append ("] " ).append (cause .reason ());
70+ }
71+ }
72+ return message .toString ();
73+ }
74+
4975 public ElasticsearchException (String endpointId , ErrorResponse response ) {
5076 this (endpointId , response , null );
5177 }
0 commit comments