Skip to content

Commit 027d120

Browse files
committed
JAVA-2100: Standardize error message when unknown BSON type is encounter during decoding.
"Detected unknown BSON type "\x16" for fieldname "a". Are you using the latest driver version?" This will help users who start using new BSON types in newer server versions, but have not yet upgraded their driver.
1 parent 2614598 commit 027d120

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

bson/src/main/org/bson/BsonBinaryReader.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,10 @@ public BsonType readBsonType() {
9090
byte bsonTypeByte = bsonInput.readByte();
9191
BsonType bsonType = BsonType.findByValue(bsonTypeByte);
9292
if (bsonType == null) {
93-
throw new BsonSerializationException(format("Expecting a valid BSON type but found %d", bsonTypeByte));
93+
String name = bsonInput.readCString();
94+
throw new BsonSerializationException(format("Detected unknown BSON type \"\\x%x\" for fieldname \"%s\". "
95+
+ "Are you using the latest driver version?",
96+
bsonTypeByte, name));
9497
}
9598
setCurrentBsonType(bsonType);
9699

bson/src/test/unit/org/bson/BsonBinaryReaderTest.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@
2323
import java.nio.ByteBuffer;
2424

2525
import static org.hamcrest.CoreMatchers.is;
26+
import static org.junit.Assert.assertEquals;
2627
import static org.junit.Assert.assertThat;
28+
import static org.junit.Assert.fail;
2729

2830
public class BsonBinaryReaderTest {
2931

@@ -41,6 +43,34 @@ public void testReadDBPointer() {
4143
reader.close();
4244
}
4345

46+
@Test
47+
public void testInvalidBsonType() {
48+
BsonBinaryReader reader = createReaderForBytes(new byte[]{26, 0, 0, 0, 22, 97, 0, 2, 0, 0, 0, 98, 0, 82, 9, 41, 108,
49+
-42, -60, -29, -116, -7, 111, -1, -36, 0});
50+
51+
reader.readStartDocument();
52+
try {
53+
reader.readBsonType();
54+
fail("Should have thrown BsonSerializationException");
55+
} catch (BsonSerializationException e) {
56+
assertEquals("Detected unknown BSON type \"\\x16\" for fieldname \"a\". Are you using the latest driver version?",
57+
e.getMessage());
58+
}
59+
}
60+
61+
@Test
62+
public void testInvalidBsonTypeFollowedByInvalidCString() {
63+
BsonBinaryReader reader = createReaderForBytes(new byte[]{26, 0, 0, 0, 22, 97, 98});
64+
65+
reader.readStartDocument();
66+
try {
67+
reader.readBsonType();
68+
fail("Should have thrown BsonSerializationException");
69+
} catch (BsonSerializationException e) {
70+
assertEquals("While decoding a BSON document 1 bytes were required, but only 0 remain", e.getMessage());
71+
}
72+
}
73+
4474
private BsonBinaryReader createReaderForBytes(final byte[] bytes) {
4575
return new BsonBinaryReader(new ByteBufferBsonInput(new ByteBufNIO(ByteBuffer.wrap(bytes))));
4676
}

0 commit comments

Comments
 (0)