{"record":{"id":"80f90e862b33a59e","repo":"JamesNK/Newtonsoft.Json","slug":"unexpected-bsontype-value-0","errorCode":null,"errorMessage":"Unexpected BsonType value: {0}","messagePattern":"Unexpected BsonType value: (.+?)","errorType":"exception","errorClass":"ArgumentOutOfRangeException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Bson/BsonReader.cs","lineNumber":568,"sourceCode":"                    SetToken(JsonToken.StartObject);\n                    _bsonReaderState = BsonReaderState.ReferenceStart;\n                    break;\n                case BsonType.Code:\n                    SetToken(JsonToken.String, ReadLengthString());\n                    break;\n                case BsonType.CodeWScope:\n                    SetToken(JsonToken.StartObject);\n                    _bsonReaderState = BsonReaderState.CodeWScopeStart;\n                    break;\n                case BsonType.Integer:\n                    SetToken(JsonToken.Integer, (long)ReadInt32());\n                    break;\n                case BsonType.TimeStamp:\n                case BsonType.Long:\n                    SetToken(JsonToken.Integer, ReadInt64());\n                    break;\n                default:\n                    throw new ArgumentOutOfRangeException(nameof(type), \"Unexpected BsonType value: \" + type);\n            }\n        }\n\n        private byte[] ReadBinary(out BsonBinaryType binaryType)\n        {\n            int dataLength = ReadInt32();\n\n            binaryType = (BsonBinaryType)ReadByte();\n\n#pragma warning disable 612,618\n            // the old binary type has the data length repeated in the data for some reason\n            if (binaryType == BsonBinaryType.BinaryOld && !_jsonNet35BinaryCompatibility)\n            {\n                dataLength = ReadInt32();\n            }\n#pragma warning restore 612,618\n\n            return ReadBytes(dataLength);","sourceCodeStart":550,"sourceCodeEnd":586,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Bson/BsonReader.cs#L550-L586","documentation":"Thrown by BsonReader.ReadType's default case when it reads a type byte from the BSON stream that does not match any known BsonType (it handles Number, String, Object, Array, Binary, Undefined, Oid, Boolean, Date, Null, Reference, Code, CodeWScope, Integer, TimeStamp, Long). It is an ArgumentOutOfRangeException reporting the raw BsonType value encountered.","triggerScenarios":"Deserializing a BSON document where an element's type byte is an unknown/invalid value. Typically the result of a corrupt BSON stream, a version mismatch (the writer used a BSON type this reader build does not recognize), or feeding non-BSON binary data into BsonReader.","commonSituations":"Feeding arbitrary binary or a different serialization format into BsonReader by mistake. Reading BSON produced by a newer/older MongoDB driver using a type code Newtonsoft's BsonReader does not support. Network corruption or truncated data causing the reader to misalign and read a data byte as a type byte.","solutions":["Verify the input stream is genuinely BSON and not another binary format.","Check the byte value reported in the message against the BSON spec; if it is a newer type (e.g. Decimal128 0x13), upgrade to the dedicated Newtonsoft.Json.Bson package or MongoDB driver.","Validate stream integrity (length prefix, CRC) before deserialization.","Ensure the writer and reader use compatible BSON type vocabularies."],"exampleFix":"// before: feeding arbitrary bytes\nusing var reader = new BsonReader(ms);\nvar obj = serializer.Deserialize(reader, typeof(Foo));\n\n// after: confirm the stream is BSON before reading\nif (!LooksLikeBson(ms)) throw new InvalidDataException(\"not BSON\");\nms.Position = 0;\nusing var reader = new BsonReader(ms);","handlingStrategy":"validation","validationCode":"byte[] data = ReadFully(stream);\nint docLen = BitConverter.ToInt32(data, 0);\nif (data.Length < docLen) throw new InvalidDataException(\"truncated BSON\");\n// optionally validate type bytes are within known BsonType range (0x01..0x12 typical)","typeGuard":"static bool IsKnownBsonType(byte t) =>\n    t == 0x01 || t == 0x02 || t == 0x03 || t == 0x04 || t == 0x05 || t == 0x06\n    || t == 0x07 || t == 0x08 || t == 0x09 || t == 0x0A || t == 0x0B || t == 0x0C\n    || t == 0x0D || t == 0x0E || t == 0x0F || t == 0x10 || t == 0x11 || t == 0x12;","tryCatchPattern":"try { var v = serializer.Deserialize(bsonReader, type); }\ncatch (ArgumentOutOfRangeException ex) when (ex.Message.Contains(\"Unexpected BsonType\"))\n{\n    throw new InvalidDataException(\"BSON stream contains an unsupported/unknown type byte\", ex);\n}","preventionTips":["Validate the stream is BSON before deserialization (check length prefix and type bytes).","Ensure writer and reader share the same BSON type vocabulary.","Upgrade to the dedicated BSON package if you need newer BSON types (Decimal128, etc.)."],"tags":["bson","deserialization","argument-out-of-range","corrupt-data"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}