2525import java .util .Optional ;
2626
2727import static com .mongodb .assertions .Assertions .isTrueArgument ;
28+ import static com .mongodb .assertions .Assertions .notNull ;
29+ import static com .mongodb .internal .operation .ClientBulkWriteOperation .Exceptions .serverAddressFromException ;
2830import static java .util .Collections .emptyList ;
2931import static java .util .Collections .emptyMap ;
3032import static java .util .Collections .unmodifiableList ;
@@ -58,14 +60,20 @@ public final class ClientBulkWriteException extends MongoServerException {
5860 * @param writeErrors The {@linkplain #getWriteErrors() write errors}.
5961 * @param partialResult The {@linkplain #getPartialResult() partial result}.
6062 * @param serverAddress The {@linkplain MongoServerException#getServerAddress() server address}.
63+ * If {@code error} is a {@link MongoServerException} or a {@link MongoSocketException}, then {@code serverAddress}
64+ * must be equal to the {@link ServerAddress} they bear.
6165 */
6266 public ClientBulkWriteException (
6367 @ Nullable final MongoException error ,
6468 @ Nullable final List <WriteConcernError > writeConcernErrors ,
6569 @ Nullable final Map <Integer , WriteError > writeErrors ,
6670 @ Nullable final ClientBulkWriteResult partialResult ,
6771 final ServerAddress serverAddress ) {
68- super (message (error , writeConcernErrors , writeErrors , partialResult , serverAddress ), serverAddress );
72+ super (
73+ message (
74+ error , writeConcernErrors , writeErrors , partialResult ,
75+ notNull ("serverAddress" , serverAddress )),
76+ validateServerAddress (error , serverAddress ));
6977 isTrueArgument ("At least one of `writeConcernErrors`, `writeErrors`, `partialResult` must be non-null or non-empty" ,
7078 !(writeConcernErrors == null || writeConcernErrors .isEmpty ())
7179 || !(writeErrors == null || writeErrors .isEmpty ())
@@ -89,6 +97,14 @@ private static String message(
8997 + (partialResult == null ? "" : " Partial result: " + partialResult + "." );
9098 }
9199
100+ private static ServerAddress validateServerAddress (@ Nullable final MongoException error , final ServerAddress serverAddress ) {
101+ serverAddressFromException (error ).ifPresent (serverAddressFromError ->
102+ isTrueArgument ("`serverAddress` must be equal to that of the `error`" , serverAddressFromError .equals (serverAddress )));
103+ return error instanceof MongoServerException
104+ ? ((MongoServerException ) error ).getServerAddress ()
105+ : serverAddress ;
106+ }
107+
92108 /**
93109 * The top-level error. That is an error that is neither a {@linkplain #getWriteConcernErrors() write concern error},
94110 * nor is an {@linkplain #getWriteErrors() error of an individual write operation}.
0 commit comments