Skip to content

Commit

Permalink
Make MongoWriteException Serializable
Browse files Browse the repository at this point in the history
Implement Serializable for WriteError. This is the only non-serializable field in MongoWriteException. Exceptions are supposed to be serializable.
  • Loading branch information
govindbalaji-s committed Jan 31, 2024
1 parent cb6692f commit 310683c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
6 changes: 5 additions & 1 deletion driver-core/src/main/com/mongodb/WriteError.java
Expand Up @@ -18,14 +18,18 @@

import org.bson.BsonDocument;

import java.io.Serializable;

import static com.mongodb.assertions.Assertions.notNull;

/**
* Represents the details of a write error , e.g. a duplicate key error
*
* @since 3.0
*/
public class WriteError {
public class WriteError implements Serializable {

private static final long serialVersionUID = 5582035144266419294L;
private final int code;
private final String message;
private final BsonDocument details;
Expand Down
Expand Up @@ -19,14 +19,23 @@

import org.bson.BsonDocument;
import org.bson.BsonInt32;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.file.Path;
import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class MongoWriteExceptionTest {

@TempDir
Path tempDir;

@Test
public void testExceptionProperties() {
WriteError writeError = new WriteError(11000, "Duplicate key", new BsonDocument("x", new BsonInt32(1)));
Expand All @@ -38,4 +47,23 @@ public void testExceptionProperties() {
assertEquals(writeError.getCode(), e.getCode());
assertEquals(writeError, e.getError());
}

@Test
public void testExceptionSerializable() throws Exception {
WriteError writeError = new WriteError(11000, "Duplicate key", new BsonDocument("x", new BsonInt32(1)));
MongoWriteException writeException = new MongoWriteException(writeError, new ServerAddress("host1"), Collections.emptySet());


Path tempPath = tempDir.resolve("testFile");
try (FileOutputStream fileOutputStream = new FileOutputStream(tempPath.toFile());
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) {
objectOutputStream.writeObject(writeException);
}

try (FileInputStream fileInputStream = new FileInputStream(tempPath.toFile());
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)) {
MongoWriteException deserializedException = (MongoWriteException) objectInputStream.readObject();
assertEquals(writeException.getError(), deserializedException.getError());
}
}
}

0 comments on commit 310683c

Please sign in to comment.