{"record":{"id":"11feca3e8e909544","repo":"JamesNK/Newtonsoft.Json","slug":"unexpected-token-when-writing-bson-0","errorCode":null,"errorMessage":"Unexpected token when writing BSON: {0}","messagePattern":"Unexpected token when writing BSON: (.+?)","errorType":"exception","errorClass":"ArgumentOutOfRangeException","httpStatus":null,"severity":"error","filePath":"Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs","lineNumber":191,"sourceCode":"                    break;\n                case BsonType.Oid:\n                {\n                    BsonValue value = (BsonValue)t;\n\n                    byte[] data = (byte[])value.Value;\n                    _writer.Write(data);\n                }\n                    break;\n                case BsonType.Regex:\n                {\n                    BsonRegex value = (BsonRegex)t;\n\n                    WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);\n                    WriteString((string)value.Options.Value, value.Options.ByteCount, null);\n                }\n                    break;\n                default:\n                    throw new ArgumentOutOfRangeException(nameof(t), \"Unexpected token when writing BSON: {0}\".FormatWith(CultureInfo.InvariantCulture, t.Type));\n            }\n        }\n\n        private void WriteString(string s, int byteCount, int? calculatedlengthPrefix)\n        {\n            if (calculatedlengthPrefix != null)\n            {\n                _writer.Write(calculatedlengthPrefix.GetValueOrDefault());\n            }\n\n            WriteUtf8Bytes(s, byteCount);\n\n            _writer.Write((byte)0);\n        }\n\n        public void WriteUtf8Bytes(string s, int byteCount)\n        {\n            if (s != null)","sourceCodeStart":173,"sourceCodeEnd":209,"githubUrl":"https://github.com/JamesNK/Newtonsoft.Json/blob/4f73e74372445108d2c1bda37b36e6f5e43402e0/Src/Newtonsoft.Json/Bson/BsonBinaryWriter.cs#L173-L209","documentation":"Thrown by BsonBinaryWriter.WriteValue's default case when it encounters a BsonToken whose Type is not one of the handled BsonType values (Object, Array, Integer, Long, Number, String, Boolean, Null, Undefined, Date, Binary, Oid, Regex). It is an ArgumentOutOfRangeException indicating the BSON writer received a token it does not know how to serialize to binary. Because BsonWriter constructs these tokens internally from public Write* calls, this normally signals an internal/unsupported value path rather than a typical user mistake.","triggerScenarios":"Calling BsonWriter methods that produce an unsupported combination, e.g. writing a value whose runtime type cannot be mapped to a known BsonType, or directly feeding a hand-constructed BsonToken tree (BsonWriter.WriteValue with a BsonObject/BsonArray tree containing an exotic token) into the writer. Also reachable when serializing an object graph that yields a token type the BSON writer never expected (e.g. a Guid that is not wrapped as Oid/Binary).","commonSituations":"Using the obsolete Newtonsoft BSON support on a data model with types BSON does not natively represent (e.g. Guid without a converter, complex nested values). Migrating from the in-box BSON to the separate Newtonsoft.Json.Bson package and hitting a behavior gap. Manually building BsonToken trees in tests.","solutions":["Inspect the exception message: the {0} placeholder is filled with the offending BsonType; remove or convert the value producing that token type.","Add a custom JsonConverter/BsonConverter for the CLR type that triggered the unsupported token so it serializes as a supported BSON primitive (string, bytes, integer).","If you are manually constructing BsonToken trees, ensure every leaf uses only supported BsonType values.","Migrate from the obsolete in-box BSON classes to the dedicated Newtonsoft.Json.Bson NuGet package."],"exampleFix":"// before: Guid property serializes to an unsupported token\nnew BsonWriter(stream);\nserializer.Serialize(bsonWriter, modelWithGuid);\n\n// after: convert Guid to a 16-byte binary value before BSON serialization\nvar settings = new JsonSerializerSettings();\nsettings.Converters.Add(new GuidToBinaryConverter()); // writes Guid as BsonType.Binary","handlingStrategy":"validation","validationCode":"// Before serializing, ensure every leaf value maps to a supported BSON primitive.\nstatic bool IsBsonSupported(object value) =>\n    value == null\n    || value is int || value is long || value is double || value is decimal\n    || value is bool || value is string || value is byte[]\n    || value is DateTime || value is DateTimeOffset\n    || value is Newtonsoft.Json.Bson.BsonObjectId;\n\nif (!graph.All(IsBsonSupported)) throw new InvalidOperationException(\"unsupported BSON type\");","typeGuard":"static bool IsSupportedBsonType(Newtonsoft.Json.Bson.BsonType t) =>\n    t == Newtonsoft.Json.Bson.BsonType.Object\n    || t == Newtonsoft.Json.Bson.BsonType.Array\n    || t == Newtonsoft.Json.Bson.BsonType.Integer\n    || t == Newtonsoft.Json.Bson.BsonType.Long\n    || t == Newtonsoft.Json.Bson.BsonType.Number\n    || t == Newtonsoft.Json.Bson.BsonType.String\n    || t == Newtonsoft.Json.Bson.BsonType.Boolean\n    || t == Newtonsoft.Json.Bson.BsonType.Null\n    || t == Newtonsoft.Json.Bson.BsonType.Undefined\n    || t == Newtonsoft.Json.Bson.BsonType.Date\n    || t == Newtonsoft.Json.Bson.BsonType.Binary\n    || t == Newtonsoft.Json.Bson.BsonType.Oid\n    || t == Newtonsoft.Json.Bson.BsonType.Regex;","tryCatchPattern":"try { serializer.Serialize(bsonWriter, obj); }\ncatch (ArgumentOutOfRangeException ex) when (ex.Message.Contains(\"Unexpected token when writing BSON\"))\n{\n    // log the offending BsonType, convert the offending value, or fall back to JSON\n    throw new InvalidOperationException(\"Unsupported BSON token type\", ex);\n}","preventionTips":["Register custom converters for CLR types BSON does not natively support (Guid, decimal, custom structs).","Avoid hand-building BsonToken trees; let BsonWriter derive tokens from your object graph.","Migrate to the dedicated Newtonsoft.Json.Bson package which supersedes the obsolete in-box types."],"tags":["bson","serialization","argument-out-of-range","writer"],"analyzedSha":"4f73e74372445108d2c1bda37b36e6f5e43402e0","analyzedAt":"2026-08-07T06:10:08.596Z","schemaVersion":2},"datasetVersion":"2026-08-07T07:17:06.508Z"}