From a7bddf989f1408facac88adefd31e433909e84be Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 21 Apr 2012 17:25:44 +1200 Subject: [PATCH] -Added Path to JsonReaderException/JsonSerializationException messages -Added JsonException -Fixed all Exceptions thrown to be more specific --- .../Bson/BsonReaderTests.cs | 33 +- .../Converters/IsoDateTimeConverterTests.cs | 2 +- .../JavaScriptDateTimeConverterTests.cs | 2 +- .../Converters/XmlNodeConverterTest.cs | 40 +- Src/Newtonsoft.Json.Tests/JsonConvertTest.cs | 2 +- .../JsonTextReaderTest.cs | 401 ++++++++-------- .../JsonTextWriterTest.cs | 76 +-- .../Linq/DynamicTests.cs | 14 +- Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs | 232 ++++----- .../Linq/JObjectTests.cs | 138 +++--- Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs | 120 ++--- .../Linq/JPropertyTests.cs | 70 +-- .../Linq/JTokenReaderTest.cs | 110 +++-- Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs | 16 +- .../Properties/AssemblyInfo.cs | 2 +- .../Serialization/DynamicTests.cs | 2 +- .../Serialization/JsonSerializerTest.cs | 447 +++++++++--------- .../MissingMemberHandlingTests.cs | 24 +- .../Serialization/PopulateTests.cs | 2 +- .../PreserveReferencesHandlingTests.cs | 50 +- .../SerializationErrorHandlingTests.cs | 16 +- .../Serialization/TypeNameHandlingTests.cs | 35 +- Src/Newtonsoft.Json.Tests/TestFixtureBase.cs | 2 +- Src/Newtonsoft.Json/Bson/BsonObjectId.cs | 2 +- Src/Newtonsoft.Json/Bson/BsonReader.cs | 12 +- Src/Newtonsoft.Json/Bson/BsonWriter.cs | 2 +- .../Converters/BinaryConverter.cs | 12 +- .../Converters/ExpandoObjectConverter.cs | 10 +- .../Converters/IsoDateTimeConverter.cs | 6 +- .../Converters/JavaScriptDateTimeConverter.cs | 10 +- .../Converters/KeyValuePairConverter.cs | 2 +- .../Converters/StringEnumConverter.cs | 6 +- .../Converters/VersionConverter.cs | 6 +- .../Converters/XmlNodeConverter.cs | 2 +- Src/Newtonsoft.Json/JsonArrayAttribute.cs | 58 +++ Src/Newtonsoft.Json/JsonConverterAttribute.cs | 2 +- Src/Newtonsoft.Json/JsonException.cs | 83 ++++ Src/Newtonsoft.Json/JsonReader.cs | 77 +-- Src/Newtonsoft.Json/JsonReaderException.cs | 51 +- .../JsonSerializationException.cs | 19 +- Src/Newtonsoft.Json/JsonTextReader.cs | 54 +-- Src/Newtonsoft.Json/JsonValidatingReader.cs | 4 +- Src/Newtonsoft.Json/JsonWriterException.cs | 2 +- Src/Newtonsoft.Json/Linq/JArray.cs | 12 +- Src/Newtonsoft.Json/Linq/JConstructor.cs | 4 +- Src/Newtonsoft.Json/Linq/JContainer.cs | 18 +- Src/Newtonsoft.Json/Linq/JObject.cs | 14 +- Src/Newtonsoft.Json/Linq/JPath.cs | 16 +- Src/Newtonsoft.Json/Linq/JProperty.cs | 14 +- Src/Newtonsoft.Json/Linq/JToken.cs | 12 +- .../Newtonsoft.Json.Net20.csproj | 1 + .../Newtonsoft.Json.Net35.csproj | 1 + .../Newtonsoft.Json.Silverlight.csproj | 1 + .../Newtonsoft.Json.WindowsPhone.csproj | 1 + Src/Newtonsoft.Json/Newtonsoft.Json.csproj | 1 + .../Properties/AssemblyInfo.cs | 2 +- .../Schema/JsonSchemaBuilder.cs | 39 +- .../Schema/JsonSchemaException.cs | 2 +- .../Schema/JsonSchemaGenerator.cs | 6 +- .../Serialization/DefaultContractResolver.cs | 14 +- .../Serialization/DefaultReferenceResolver.cs | 2 +- .../Serialization/DynamicValueProvider.cs | 4 +- .../JsonSerializerInternalReader.cs | 109 ++--- .../Utilities/CollectionUtils.cs | 6 +- .../Utilities/CollectionWrapper.cs | 10 +- Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 6 +- .../DynamicReflectionDelegateFactory.cs | 4 +- Src/Newtonsoft.Json/Utilities/DynamicUtils.cs | 2 +- Src/Newtonsoft.Json/Utilities/EnumUtils.cs | 4 +- 69 files changed, 1400 insertions(+), 1161 deletions(-) create mode 100644 Src/Newtonsoft.Json/JsonException.cs diff --git a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs index 56440241..55de1124 100644 --- a/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs +++ b/Src/Newtonsoft.Json.Tests/Bson/BsonReaderTests.cs @@ -275,28 +275,29 @@ namespace Newtonsoft.Json.Tests.Bson [Test] public void ReadAsInt32BadString() { - ExceptionAssert.Throws("Could not convert string to integer: a.", - () => - { - byte[] data = MiscellaneousUtils.HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00"); + ExceptionAssert.Throws( + "Could not convert string to integer: a. Path '[0]'.", + () => + { + byte[] data = MiscellaneousUtils.HexToBytes("20-00-00-00-02-30-00-02-00-00-00-61-00-02-31-00-02-00-00-00-62-00-02-32-00-02-00-00-00-63-00-00"); - MemoryStream ms = new MemoryStream(data); - BsonReader reader = new BsonReader(ms); + MemoryStream ms = new MemoryStream(data); + BsonReader reader = new BsonReader(ms); - Assert.AreEqual(false, reader.ReadRootValueAsArray); - Assert.AreEqual(DateTimeKind.Local, reader.DateTimeKindHandling); + Assert.AreEqual(false, reader.ReadRootValueAsArray); + Assert.AreEqual(DateTimeKind.Local, reader.DateTimeKindHandling); - reader.ReadRootValueAsArray = true; - reader.DateTimeKindHandling = DateTimeKind.Utc; + reader.ReadRootValueAsArray = true; + reader.DateTimeKindHandling = DateTimeKind.Utc; - Assert.AreEqual(true, reader.ReadRootValueAsArray); - Assert.AreEqual(DateTimeKind.Utc, reader.DateTimeKindHandling); + Assert.AreEqual(true, reader.ReadRootValueAsArray); + Assert.AreEqual(DateTimeKind.Utc, reader.DateTimeKindHandling); - Assert.IsTrue(reader.Read()); - Assert.AreEqual(JsonToken.StartArray, reader.TokenType); + Assert.IsTrue(reader.Read()); + Assert.AreEqual(JsonToken.StartArray, reader.TokenType); - reader.ReadAsInt32(); - }); + reader.ReadAsInt32(); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs index ff64523c..4b13bd72 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/IsoDateTimeConverterTests.cs @@ -217,7 +217,7 @@ namespace Newtonsoft.Json.Tests.Converters [Test] public void DeserializeNullToNonNullable() { - ExceptionAssert.Throws("Cannot convert null value to System.DateTime.", + ExceptionAssert.Throws("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.", () => { DateTimeTestClass c2 = diff --git a/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs b/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs index f9513fe2..bc6e4edb 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/JavaScriptDateTimeConverterTests.cs @@ -100,7 +100,7 @@ namespace Newtonsoft.Json.Tests.Converters [Test] public void DeserializeNullToNonNullable() { - ExceptionAssert.Throws("Cannot convert null value to System.DateTime.", + ExceptionAssert.Throws("Cannot convert null value to System.DateTime. Path 'DateTimeField', line 1, position 38.", () => { DateTimeTestClass c2 = diff --git a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs index 6ec45ce8..6f7fc6b5 100644 --- a/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs +++ b/Src/Newtonsoft.Json.Tests/Converters/XmlNodeConverterTest.cs @@ -491,17 +491,25 @@ namespace Newtonsoft.Json.Tests.Converters } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "XmlNodeConverter can only convert JSON that begins with an object.")] public void NoRootObject() { - XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"[1]"); + ExceptionAssert.Throws( + "XmlNodeConverter can only convert JSON that begins with an object.", + () => + { + XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"[1]"); + }); } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.")] public void RootObjectMultipleProperties() { - XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); + ExceptionAssert.Throws( + "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.", + () => + { + XmlDocument newDoc = (XmlDocument)JsonConvert.DeserializeXmlNode(@"{Prop1:1,Prop2:2}"); + }); } [Test] @@ -613,22 +621,30 @@ namespace Newtonsoft.Json.Tests.Converters } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.")] public void MultipleRootPropertiesXmlDocument() { string json = @"{""count"": 773840,""photos"": null}"; - JsonConvert.DeserializeXmlNode(json); + ExceptionAssert.Throws( + "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.", + () => + { + JsonConvert.DeserializeXmlNode(json); + }); } #if !NET20 [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.")] public void MultipleRootPropertiesXDocument() { string json = @"{""count"": 773840,""photos"": null}"; - JsonConvert.DeserializeXNode(json); + ExceptionAssert.Throws( + "JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.", + () => + { + JsonConvert.DeserializeXNode(json); + }); } #endif @@ -1008,7 +1024,6 @@ namespace Newtonsoft.Json.Tests.Converters } [Test] - [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "XmlNodeConverter cannot convert JSON with an empty property name to XML.")] public void EmptyPropertyName() { string json = @"{ @@ -1090,7 +1105,12 @@ namespace Newtonsoft.Json.Tests.Converters } }"; - DeserializeXmlNode(json); + ExceptionAssert.Throws( + "XmlNodeConverter cannot convert JSON with an empty property name to XML.", + () => + { + DeserializeXmlNode(json); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs index dbd3f2b9..db6b00e5 100644 --- a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs @@ -303,7 +303,7 @@ now brown cow?", '"', true); [Test] public void TestInvalidStrings() { - ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: t. Line 1, position 19.", + ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: t. Path '', line 1, position 19.", () => { string orig = @"this is a string ""that has quotes"" "; diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs index eb06d293..19988473 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs @@ -189,11 +189,6 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2." -#endif - )] public void ParseAdditionalContent_Comma() { string json = @"[ @@ -203,17 +198,18 @@ namespace Newtonsoft.Json.Tests ],"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); - while (reader.Read()) - { - } + + ExceptionAssert.Throws( + "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.", + () => + { + while (reader.Read()) + { + } + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Additional text encountered after finished reading JSON content: c. Line 5, position 2." -#endif - )] public void ParseAdditionalContent_Text() { string json = @"[ @@ -240,7 +236,12 @@ namespace Newtonsoft.Json.Tests reader.Read(); Assert.AreEqual(5, reader.LineNumber); - reader.Read(); + ExceptionAssert.Throws( + "Additional text encountered after finished reading JSON content: c. Path '', line 5, position 2.", + () => + { + reader.Read(); + }); } [Test] @@ -261,19 +262,20 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Additional text encountered after finished reading JSON content: a. Line 1, position 5." -#endif - )] public void ParseAdditionalContent_WhitespaceThenText() { string json = @"'hi' a"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); - while (reader.Read()) - { - } + + ExceptionAssert.Throws( + "Additional text encountered after finished reading JSON content: a. Path '', line 1, position 5.", + () => + { + while (reader.Read()) + { + } + }); } [Test] @@ -483,27 +485,28 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(ArgumentNullException) -#if !NETFX_CORE - , ExpectedMessage = @"Value cannot be null. -Parameter name: reader" -#endif - )] public void NullTextReader() { - new JsonTextReader(null); + ExceptionAssert.Throws( + @"Value cannot be null. +Parameter name: reader", + () => + { + new JsonTextReader(null); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3." -#endif - )] public void UnexpectedEndOfString() { JsonReader reader = new JsonTextReader(new StringReader("'hi")); - reader.Read(); + + ExceptionAssert.Throws( + "Unterminated string. Expected delimiter: '. Path '', line 1, position 3.", + () => + { + reader.Read(); + }); } [Test] @@ -664,54 +667,58 @@ Parameter name: reader" } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end while parsing unicode character. Line 1, position 4." -#endif - )] public void UnexpectedEndOfHex() { JsonReader reader = new JsonTextReader(new StringReader(@"'h\u123")); - reader.Read(); + + ExceptionAssert.Throws( + "Unexpected end while parsing unicode character. Path '', line 1, position 4.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 3." -#endif - )] public void UnexpectedEndOfControlCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"'h\")); - reader.Read(); + + ExceptionAssert.Throws( + "Unterminated string. Expected delimiter: '. Path '', line 1, position 3.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading bytes. Unexpected token: Boolean. Line 1, position 4." -#endif - )] public void ReadBytesWithBadCharacter() { JsonReader reader = new JsonTextReader(new StringReader(@"true")); - reader.ReadAsBytes(); + + ExceptionAssert.Throws( + "Error reading bytes. Unexpected token: Boolean. Path '', line 1, position 4.", + () => + { + reader.ReadAsBytes(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unterminated string. Expected delimiter: '. Line 1, position 17." -#endif - )] public void ReadBytesWithUnexpectedEnd() { string helloWorld = "Hello world!"; byte[] helloWorldData = Encoding.UTF8.GetBytes(helloWorld); JsonReader reader = new JsonTextReader(new StringReader(@"'" + Convert.ToBase64String(helloWorldData))); - reader.ReadAsBytes(); + + ExceptionAssert.Throws( + "Unterminated string. Expected delimiter: '. Path '', line 1, position 17.", + () => + { + reader.ReadAsBytes(); + }); } [Test] @@ -725,16 +732,17 @@ Parameter name: reader" } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end while parsing unquoted property name. Line 1, position 4." -#endif - )] public void UnexpectedEndWhenParsingUnquotedProperty() { JsonReader reader = new JsonTextReader(new StringReader(@"{aww")); Assert.IsTrue(reader.Read()); - reader.Read(); + + ExceptionAssert.Throws( + "Unexpected end while parsing unquoted property name. Path '', line 1, position 4.", + () => + { + reader.Read(); + }); } [Test] @@ -1193,11 +1201,6 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = @"Invalid character after parsing property name. Expected ':' but got: "". Line 3, position 9." -#endif - )] public void MissingColon() { string json = @"{ @@ -1215,7 +1218,12 @@ bye", reader.Value); reader.Read(); Assert.AreEqual(JsonToken.Boolean, reader.TokenType); - reader.Read(); + ExceptionAssert.Throws( + @"Invalid character after parsing property name. Expected ':' but got: "". Path 'A', line 3, position 9.", + () => + { + reader.Read(); + }); } [Test] @@ -1289,17 +1297,18 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected character encountered while parsing value: }. Line 1, position 1." -#endif - )] public void ReadBadCharInArray() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[}")); reader.Read(); - reader.Read(); + + ExceptionAssert.Throws( + "Unexpected character encountered while parsing value: }. Path '', line 1, position 1.", + () => + { + reader.Read(); + }); } [Test] @@ -1321,16 +1330,16 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 1." -#endif - )] public void ReadAsBytesNoContentWrappedObject() { JsonTextReader reader = new JsonTextReader(new StringReader(@"{")); - reader.ReadAsBytes(); + ExceptionAssert.Throws( + "Unexpected end when reading bytes. Path '', line 1, position 1.", + () => + { + reader.ReadAsBytes(); + }); } #if !NET20 @@ -1345,44 +1354,43 @@ bye", reader.Value); #endif [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading decimal. Unexpected token: StartConstructor. Line 1, position 9." -#endif - )] public void ReadAsDecimalBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); - Assert.IsNull(reader.ReadAsDecimal()); - Assert.AreEqual(JsonToken.None, reader.TokenType); + ExceptionAssert.Throws( + "Error reading decimal. Unexpected token: StartConstructor. Path '', line 1, position 9.", + () => + { + reader.ReadAsDecimal(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading bytes. Unexpected token: StartConstructor. Line 1, position 9." -#endif - )] public void ReadAsBytesBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); - reader.ReadAsBytes(); + ExceptionAssert.Throws( + "Error reading bytes. Unexpected token: StartConstructor. Path '', line 1, position 9.", + () => + { + reader.ReadAsBytes(); + }); } #if !NET20 [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading date. Unexpected token: StartConstructor. Line 1, position 9." -#endif - )] public void ReadAsDateTimeOffsetBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"new Date()")); - reader.ReadAsDateTimeOffset(); + ExceptionAssert.Throws( + "Error reading date. Unexpected token: StartConstructor. Path '', line 1, position 9.", + () => + { + reader.ReadAsDateTimeOffset(); + }); } #endif @@ -1398,29 +1406,29 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end when reading bytes. Line 1, position 2." -#endif - )] public void ReadAsBytesIntegerArrayWithNoEnd() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[1")); - reader.ReadAsBytes(); + ExceptionAssert.Throws( + "Unexpected end when reading bytes. Path '[0]', line 1, position 2.", + () => + { + reader.ReadAsBytes(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected token when reading bytes: Float. Line 1, position 4." -#endif - )] public void ReadAsBytesArrayWithBadContent() { JsonTextReader reader = new JsonTextReader(new StringReader(@"[1.0]")); - reader.ReadAsBytes(); + ExceptionAssert.Throws( + "Unexpected token when reading bytes: Float. Path '[0]', line 1, position 4.", + () => + { + reader.ReadAsBytes(); + }); } [Test] @@ -1515,11 +1523,6 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22." -#endif - )] public void ReadAsDateTimeOffsetBadString() { string json = @"{""Offset"":""blablahbla""}"; @@ -1532,7 +1535,12 @@ bye", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsDateTimeOffset(); + ExceptionAssert.Throws( + "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.", + () => + { + reader.ReadAsDateTimeOffset(); + }); } [Test] @@ -1672,11 +1680,6 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(FormatException) -#if !NETFX_CORE - , ExpectedMessage = "Input string was not in a correct format." -#endif - )] public void ReadAsIntDecimal() { string json = @"{""Name"": 1.1}"; @@ -1689,70 +1692,77 @@ bye", reader.Value); Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsInt32(); - Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(typeof(int), reader.ValueType); - Assert.AreEqual(1, reader.Value); + ExceptionAssert.Throws( + "Input string was not in a correct format.", + () => + { + reader.ReadAsInt32(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error parsing null value. Line 0, position 0." -#endif - )] public void MatchWithInsufficentCharacters() { JsonTextReader reader = new JsonTextReader(new StringReader(@"nul")); - reader.Read(); + + ExceptionAssert.Throws( + "Error parsing null value. Path '', line 0, position 0.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error parsing null value. Line 0, position 0." -#endif - )] public void MatchWithWrongCharacters() { JsonTextReader reader = new JsonTextReader(new StringReader(@"nulz")); - reader.Read(); + + ExceptionAssert.Throws( + "Error parsing null value. Path '', line 0, position 0.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error parsing null value. Line 1, position 4." -#endif - )] public void MatchWithNoTrailingSeperator() { JsonTextReader reader = new JsonTextReader(new StringReader(@"nullz")); - reader.Read(); + + ExceptionAssert.Throws( + "Error parsing null value. Path '', line 1, position 4.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end while parsing comment. Line 1, position 6." -#endif - )] public void UnclosedComment() { JsonTextReader reader = new JsonTextReader(new StringReader(@"/* sdf")); - reader.Read(); + + ExceptionAssert.Throws( + "Unexpected end while parsing comment. Path '', line 1, position 6.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error parsing comment. Expected: *, got s. Line 1, position 1." -#endif - )] public void BadCommentStart() { JsonTextReader reader = new JsonTextReader(new StringReader(@"/sdf")); - reader.Read(); + + ExceptionAssert.Throws( + "Error parsing comment. Expected: *, got s. Path '', line 1, position 1.", + () => + { + reader.Read(); + }); } [Test] @@ -1924,31 +1934,31 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end while parsing constructor. Line 1, position 7." -#endif - )] public void ParseConstructorWithUnexpectedEnd() { string json = "new Dat"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); - reader.Read(); + ExceptionAssert.Throws( + "Unexpected end while parsing constructor. Path '', line 1, position 7.", + () => + { + reader.Read(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected character while parsing constructor: !. Line 1, position 9." -#endif - )] public void ParseConstructorWithUnexpectedCharacter() { string json = "new Date !"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); - reader.Read(); + ExceptionAssert.Throws( + "Unexpected character while parsing constructor: !. Path '', line 1, position 9.", + () => + { + reader.Read(); + }); } [Test] @@ -1990,16 +2000,16 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error parsing boolean value. Line 1, position 4." -#endif - )] public void ParseIncompleteCommentSeperator() { JsonTextReader reader = new JsonTextReader(new StringReader("true/")); - reader.Read(); + ExceptionAssert.Throws( + "Error parsing boolean value. Path '', line 1, position 4.", + () => + { + reader.Read(); + }); } [Test] @@ -2016,17 +2026,17 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected character while parsing constructor: ,. Line 1, position 8." -#endif - )] public void ParseConstructorWithBadCharacter() { string json = "new Date,()"; JsonTextReader reader = new JsonTextReader(new StringReader(json)); - Assert.IsTrue(reader.Read()); + ExceptionAssert.Throws( + "Unexpected character while parsing constructor: ,. Path '', line 1, position 8.", + () => + { + Assert.IsTrue(reader.Read()); + }); } [Test] @@ -2181,17 +2191,18 @@ bye", reader.Value); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Additional text encountered after finished reading JSON content: }. Line 1, position 2." -#endif - )] public void UnexpectedEndTokenWhenParsingOddEndToken() { - JsonReader reader = new JsonTextReader(new StringReader(@"{}}")); - Assert.IsTrue(reader.Read()); - Assert.IsTrue(reader.Read()); - reader.Read(); + JsonReader reader = new JsonTextReader(new StringReader(@"{}}")); + Assert.IsTrue(reader.Read()); + Assert.IsTrue(reader.Read()); + + ExceptionAssert.Throws( + "Additional text encountered after finished reading JSON content: }. Path '', line 1, position 2.", + () => + { + reader.Read(); + }); } [Test] @@ -2275,7 +2286,7 @@ bye", reader.Value); Assert.IsTrue(reader.Read()); ExceptionAssert.Throws( - "The reader's MaxDepth of 1 has been exceeded. Line 1, position 2.", + "The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.", () => { Assert.IsTrue(reader.Read()); @@ -2296,7 +2307,7 @@ bye", reader.Value); Assert.AreEqual(0, reader.Depth); ExceptionAssert.Throws( - "The reader's MaxDepth of 1 has been exceeded. Line 1, position 2.", + "The reader's MaxDepth of 1 has been exceeded. Path '[0]', line 1, position 2.", () => { Assert.IsTrue(reader.Read()); @@ -2319,7 +2330,7 @@ bye", reader.Value); Assert.AreEqual(1, reader.Depth); ExceptionAssert.Throws( - "The reader's MaxDepth of 1 has been exceeded. Line 1, position 9.", + "The reader's MaxDepth of 1 has been exceeded. Path '[1]', line 1, position 9.", () => { Assert.IsTrue(reader.Read()); diff --git a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs index a1f2148f..c6cb85b0 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs @@ -172,20 +172,20 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation." -#endif - )] public void WriteValueObjectWithUnsupportedValue() { - StringWriter sw = new StringWriter(); - using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) - { - jsonWriter.WriteStartArray(); - jsonWriter.WriteValue(new Version(1, 1, 1, 1)); - jsonWriter.WriteEndArray(); - } + ExceptionAssert.Throws( + @"Unsupported type: System.Version. Use the JsonSerializer class to get the object's JSON representation.", + () => + { + StringWriter sw = new StringWriter(); + using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) + { + jsonWriter.WriteStartArray(); + jsonWriter.WriteValue(new Version(1, 1, 1, 1)); + jsonWriter.WriteEndArray(); + } + }); } [Test] @@ -594,43 +594,43 @@ namespace Newtonsoft.Json.Tests } [Test] - [ExpectedException(typeof(JsonWriterException) -#if !NETFX_CORE - , ExpectedMessage = "No token to close." -#endif - )] public void BadWriteEndArray() { - StringBuilder sb = new StringBuilder(); - StringWriter sw = new StringWriter(sb); + ExceptionAssert.Throws( + "No token to close.", + () => + { + StringBuilder sb = new StringBuilder(); + StringWriter sw = new StringWriter(sb); - using (JsonWriter jsonWriter = new JsonTextWriter(sw)) - { - jsonWriter.WriteStartArray(); + using (JsonWriter jsonWriter = new JsonTextWriter(sw)) + { + jsonWriter.WriteStartArray(); - jsonWriter.WriteValue(0.0); + jsonWriter.WriteValue(0.0); - jsonWriter.WriteEndArray(); - jsonWriter.WriteEndArray(); - } + jsonWriter.WriteEndArray(); + jsonWriter.WriteEndArray(); + } + }); } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"Invalid JavaScript string quote character. Valid quote characters are ' and ""." -#endif - )] public void InvalidQuoteChar() { - StringBuilder sb = new StringBuilder(); - StringWriter sw = new StringWriter(sb); + ExceptionAssert.Throws( + @"Invalid JavaScript string quote character. Valid quote characters are ' and "".", + () => + { + StringBuilder sb = new StringBuilder(); + StringWriter sw = new StringWriter(sb); - using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) - { - jsonWriter.Formatting = Formatting.Indented; - jsonWriter.QuoteChar = '*'; - } + using (JsonTextWriter jsonWriter = new JsonTextWriter(sw)) + { + jsonWriter.Formatting = Formatting.Indented; + jsonWriter.QuoteChar = '*'; + } + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs index 5f7d1360..bea87fad 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/DynamicTests.cs @@ -86,16 +86,16 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = "Could not determine JSON object type for type System.String[]." -#endif - )] public void JObjectPropertyNameWithNonToken() { - dynamic d = new JObject(); + ExceptionAssert.Throws( + "Could not determine JSON object type for type System.String[].", + () => + { + dynamic d = new JObject(); - d.First = new [] {"One", "II", "3"}; + d.First = new[] { "One", "II", "3" }; + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs index 5743ab3e..15b496d7 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JArrayTests.cs @@ -23,7 +23,7 @@ namespace Newtonsoft.Json.Tests.Linq [Test] public void Clear() { - JArray a = new JArray { 1 }; + JArray a = new JArray {1}; Assert.AreEqual(1, a.Count); a.Clear(); @@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Tests.Linq { JValue v = new JValue(1); - JArray a = new JArray { v }; + JArray a = new JArray {v}; Assert.AreEqual(false, a.Contains(new JValue(2))); Assert.AreEqual(false, a.Contains(new JValue(1))); @@ -63,64 +63,62 @@ namespace Newtonsoft.Json.Tests.Linq JToken[] a = new JToken[5]; - ((ICollection)j).CopyTo(a, 1); + ((ICollection) j).CopyTo(a, 1); Assert.AreEqual(null, a[0]); - Assert.AreEqual(1, (int)a[1]); + Assert.AreEqual(1, (int) a[1]); - Assert.AreEqual(2, (int)a[2]); + Assert.AreEqual(2, (int) a[2]); - Assert.AreEqual(3, (int)a[3]); + Assert.AreEqual(3, (int) a[3]); Assert.AreEqual(null, a[4]); } [Test] - [ExpectedException(typeof(ArgumentNullException) -#if !NETFX_CORE - , ExpectedMessage = @"Value cannot be null. -Parameter name: array" -#endif - )] public void GenericCollectionCopyToNullArrayShouldThrow() { JArray j = new JArray(); - ((ICollection)j).CopyTo(null, 0); + + ExceptionAssert.Throws( + @"Value cannot be null. +Parameter name: array", + () => + { + ((ICollection) j).CopyTo(null, 0); + }); } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"arrayIndex is less than 0. -Parameter name: arrayIndex" -#endif - )] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { JArray j = new JArray(); - ((ICollection)j).CopyTo(new JToken[1], -1); + + ExceptionAssert.Throws( + @"arrayIndex is less than 0. +Parameter name: arrayIndex", + () => + { + ((ICollection) j).CopyTo(new JToken[1], -1); + }); } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"arrayIndex is equal to or greater than the length of array." -#endif - )] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { JArray j = new JArray(); - ((ICollection)j).CopyTo(new JToken[1], 1); + + ExceptionAssert.Throws( + @"arrayIndex is equal to or greater than the length of array.", + () => + { + ((ICollection) j).CopyTo(new JToken[1], 1); + }); } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array." -#endif - )] public void GenericCollectionCopyToInsufficientArrayCapacity() { JArray j = new JArray(); @@ -128,7 +126,12 @@ Parameter name: arrayIndex" j.Add(new JValue(2)); j.Add(new JValue(3)); - ((ICollection)j).CopyTo(new JToken[3], 1); + ExceptionAssert.Throws( + @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.", + () => + { + ((ICollection)j).CopyTo(new JToken[3], 1); + }); } [Test] @@ -200,29 +203,31 @@ Parameter name: arrayIndex" } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"Index is equal to or greater than Count. -Parameter name: index" -#endif - )] public void RemoveAtOutOfRangeIndexShouldError() { JArray j = new JArray(); - j.RemoveAt(0); + + ExceptionAssert.Throws( + @"Index is equal to or greater than Count. +Parameter name: index", + () => + { + j.RemoveAt(0); + }); } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"Index is less than 0. -Parameter name: index" -#endif - )] public void RemoveAtNegativeIndexShouldError() { JArray j = new JArray(); - j.RemoveAt(-1); + + ExceptionAssert.Throws( + @"Index is less than 0. +Parameter name: index", + () => + { + j.RemoveAt(-1); + }); } [Test] @@ -292,33 +297,35 @@ Parameter name: index" JArray j = new JArray(); j.Insert(0, null); - Assert.AreEqual(null, ((JValue)j[0]).Value); + Assert.AreEqual(null, ((JValue) j[0]).Value); } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"Index was out of range. Must be non-negative and less than the size of the collection. -Parameter name: index" -#endif - )] public void InsertNegativeIndexShouldThrow() { JArray j = new JArray(); - j.Insert(-1, new JValue(1)); + + ExceptionAssert.Throws( + @"Index was out of range. Must be non-negative and less than the size of the collection. +Parameter name: index", + () => + { + j.Insert(-1, new JValue(1)); + }); } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"Index must be within the bounds of the List. -Parameter name: index" -#endif - )] public void InsertOutOfRangeIndexShouldThrow() { JArray j = new JArray(); - j.Insert(2, new JValue(1)); + + ExceptionAssert.Throws( + @"Index must be within the bounds of the List. +Parameter name: index", + () => + { + j.Insert(2, new JValue(1)); + }); } [Test] @@ -344,15 +351,16 @@ Parameter name: index" } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject" -#endif - )] public void Parse_ShouldThrowOnUnexpectedToken() { string json = @"{""prop"":""value""}"; - JArray.Parse(json); + + ExceptionAssert.Throws( + "Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. Path '', line 1, position 1.", + () => + { + JArray.Parse(json); + }); } public class ListItemFields @@ -367,24 +375,24 @@ Parameter name: index" string itemZeroText = "Zero text"; IEnumerable t = new List - { - new ListItemFields { ListItemText = "First", ListItemValue = 1 }, - new ListItemFields { ListItemText = "Second", ListItemValue = 2 }, - new ListItemFields { ListItemText = "Third", ListItemValue = 3 } - }; + { + new ListItemFields {ListItemText = "First", ListItemValue = 1}, + new ListItemFields {ListItemText = "Second", ListItemValue = 2}, + new ListItemFields {ListItemText = "Third", ListItemValue = 3} + }; JObject optionValues = - new JObject( - new JProperty("options", - new JArray( - new JObject( - new JProperty("text", itemZeroText), - new JProperty("value", "0")), + new JObject( + new JProperty("options", + new JArray( + new JObject( + new JProperty("text", itemZeroText), + new JProperty("value", "0")), from r in t orderby r.ListItemValue select new JObject( - new JProperty("text", r.ListItemText), - new JProperty("value", r.ListItemValue.ToString()))))); + new JProperty("text", r.ListItemText), + new JProperty("value", r.ListItemValue.ToString()))))); string result = "myOptions = " + optionValues.ToString(); @@ -418,12 +426,12 @@ Parameter name: index" int i = 1; foreach (JToken token in a) { - Assert.AreEqual(i, (int)token); + Assert.AreEqual(i, (int) token); i++; } } - + #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) [Test] public void ITypedListGetItemProperties() @@ -447,21 +455,21 @@ Parameter name: index" a.Add(a); Assert.AreEqual(3, a.Count); - Assert.AreEqual(1, (int)a[0]); - Assert.AreEqual(2, (int)a[1]); + Assert.AreEqual(1, (int) a[0]); + Assert.AreEqual(2, (int) a[1]); Assert.AreNotSame(a, a[2]); } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"Set JArray values with invalid key value: ""badvalue"". Array position index expected." -#endif - )] public void SetValueWithInvalidIndex() { - JArray a = new JArray(); - a["badvalue"] = new JValue(3); + ExceptionAssert.Throws( + @"Set JArray values with invalid key value: ""badvalue"". Array position index expected.", + () => + { + JArray a = new JArray(); + a["badvalue"] = new JValue(3); + }); } [Test] @@ -469,35 +477,35 @@ Parameter name: index" { object key = 0; - JArray a = new JArray((object)null); + JArray a = new JArray((object) null); a[key] = new JValue(3); - Assert.AreEqual(3, (int)a[key]); + Assert.AreEqual(3, (int) a[key]); } [Test] public void ReplaceAll() { - JArray a = new JArray(new [] { 1, 2, 3 }); + JArray a = new JArray(new[] {1, 2, 3}); Assert.AreEqual(3, a.Count); - Assert.AreEqual(1, (int)a[0]); - Assert.AreEqual(2, (int)a[1]); - Assert.AreEqual(3, (int)a[2]); + Assert.AreEqual(1, (int) a[0]); + Assert.AreEqual(2, (int) a[1]); + Assert.AreEqual(3, (int) a[2]); a.ReplaceAll(1); Assert.AreEqual(1, a.Count); - Assert.AreEqual(1, (int)a[0]); + Assert.AreEqual(1, (int) a[0]); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected end of content while loading JArray." -#endif - )] public void ParseIncomplete() { - JArray.Parse("[1"); + ExceptionAssert.Throws( + "Unexpected end of content while loading JArray. Path '[0]', line 1, position 2.", + () => + { + JArray.Parse("[1"); + }); } [Test] @@ -508,16 +516,11 @@ Parameter name: index" array.Insert(1, 456); Assert.AreEqual(2, array.Count); - Assert.AreEqual(123, (int)array[0]); - Assert.AreEqual(456, (int)array[1]); + Assert.AreEqual(123, (int) array[0]); + Assert.AreEqual(456, (int) array[1]); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Additional text encountered after finished reading JSON content: ,. Line 5, position 2." -#endif - )] public void ParseAdditionalContent() { string json = @"[ @@ -526,7 +529,12 @@ Parameter name: index" ""Large"" ], 987987"; - JArray.Parse(json); + ExceptionAssert.Throws( + "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.", + () => + { + JArray.Parse(json); + }); } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs index 7be89521..8c56ea94 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JObjectTests.cs @@ -113,16 +113,16 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object." -#endif - )] public void DuplicatePropertyNameShouldThrow() { - JObject o = new JObject(); - o.Add("PropertyNameValue", null); - o.Add("PropertyNameValue", null); + ExceptionAssert.Throws( + "Can not add property PropertyNameValue to Newtonsoft.Json.Linq.JObject. Property with the same name already exists on object.", + () => + { + JObject o = new JObject(); + o.Add("PropertyNameValue", null); + o.Add("PropertyNameValue", null); + }); } [Test] @@ -227,57 +227,57 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentNullException) -#if !NETFX_CORE - , ExpectedMessage = @"Value cannot be null. -Parameter name: array" -#endif - )] public void GenericCollectionCopyToNullArrayShouldThrow() { - JObject o = new JObject(); - ((ICollection>)o).CopyTo(null, 0); + ExceptionAssert.Throws( + @"Value cannot be null. +Parameter name: array", + () => + { + JObject o = new JObject(); + ((ICollection>)o).CopyTo(null, 0); + }); } [Test] - [ExpectedException(typeof(ArgumentOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"arrayIndex is less than 0. -Parameter name: arrayIndex" -#endif - )] public void GenericCollectionCopyToNegativeArrayIndexShouldThrow() { - JObject o = new JObject(); - ((ICollection>)o).CopyTo(new KeyValuePair[1], -1); + ExceptionAssert.Throws( + @"arrayIndex is less than 0. +Parameter name: arrayIndex", + () => + { + JObject o = new JObject(); + ((ICollection>)o).CopyTo(new KeyValuePair[1], -1); + }); } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"arrayIndex is equal to or greater than the length of array." -#endif - )] public void GenericCollectionCopyToArrayIndexEqualGreaterToArrayLengthShouldThrow() { - JObject o = new JObject(); - ((ICollection>)o).CopyTo(new KeyValuePair[1], 1); + ExceptionAssert.Throws( + @"arrayIndex is equal to or greater than the length of array.", + () => + { + JObject o = new JObject(); + ((ICollection>)o).CopyTo(new KeyValuePair[1], 1); + }); } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array." -#endif - )] public void GenericCollectionCopyToInsufficientArrayCapacity() { - JObject o = new JObject(); - o.Add("PropertyNameValue", new JValue(1)); - o.Add("PropertyNameValue2", new JValue(2)); - o.Add("PropertyNameValue3", new JValue(3)); + ExceptionAssert.Throws( + @"The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array.", + () => + { + JObject o = new JObject(); + o.Add("PropertyNameValue", new JValue(1)); + o.Add("PropertyNameValue2", new JValue(2)); + o.Add("PropertyNameValue3", new JValue(3)); - ((ICollection>)o).CopyTo(new KeyValuePair[3], 1); + ((ICollection>)o).CopyTo(new KeyValuePair[3], 1); + }); } [Test] @@ -363,7 +363,7 @@ Parameter name: arrayIndex" [Test] public void Parse_ShouldThrowOnUnexpectedToken() { - ExceptionAssert.Throws("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray", + ExceptionAssert.Throws("Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.", () => { string json = @"[""prop""]"; @@ -400,15 +400,13 @@ Parameter name: arrayIndex" public void Blog() { ExceptionAssert.Throws( - "Invalid property identifier character: ]. Line 3, position 5.", + "Invalid property identifier character: ]. Path 'name', line 3, position 5.", () => { - JObject person = JObject.Parse(@"{ + JObject.Parse(@"{ ""name"": ""James"", ]!#$THIS IS: BAD JSON![{}}}}] }"); - - // Invalid property identifier character: ]. Line 3, position 9. }); } @@ -1271,19 +1269,27 @@ Parameter name: arrayIndex" } [Test] - [ExpectedException(typeof(NotSupportedException))] public void IBindingListApplySort() { - IBindingList l = new JObject(); - l.ApplySort(null, ListSortDirection.Ascending); + ExceptionAssert.Throws( + "Specified method is not supported.", + () => + { + IBindingList l = new JObject(); + l.ApplySort(null, ListSortDirection.Ascending); + }); } [Test] - [ExpectedException(typeof(NotSupportedException))] public void IBindingListRemoveSort() { - IBindingList l = new JObject(); - l.RemoveSort(); + ExceptionAssert.Throws( + "Specified method is not supported.", + () => + { + IBindingList l = new JObject(); + l.RemoveSort(); + }); } [Test] @@ -1295,11 +1301,15 @@ Parameter name: arrayIndex" } [Test] - [ExpectedException(typeof(NotSupportedException))] public void IBindingListFind() { - IBindingList l = new JObject(); - l.Find(null, null); + ExceptionAssert.Throws( + "Specified method is not supported.", + () => + { + IBindingList l = new JObject(); + l.Find(null, null); + }); } [Test] @@ -1310,11 +1320,15 @@ Parameter name: arrayIndex" } [Test] - [ExpectedException(typeof(Exception), ExpectedMessage = "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.")] public void IBindingListAddNew() { - IBindingList l = new JObject(); - l.AddNew(); + ExceptionAssert.Throws( + "Could not determine new value to add to 'Newtonsoft.Json.Linq.JObject'.", + () => + { + IBindingList l = new JObject(); + l.AddNew(); + }); } [Test] @@ -1580,7 +1594,7 @@ Parameter name: arrayIndex" [Test] public void NumberTooBigForInt64() { - ExceptionAssert.Throws("JSON integer 307953220000517141511 is too large or small for an Int64. Line 1, position 30.", + ExceptionAssert.Throws("JSON integer 307953220000517141511 is too large or small for an Int64. Path 'code', line 1, position 30.", () => { string json = @"{""code"": 307953220000517141511}"; @@ -1592,7 +1606,7 @@ Parameter name: arrayIndex" [Test] public void ParseIncomplete() { - ExceptionAssert.Throws("Unexpected end of content while loading JObject.", + ExceptionAssert.Throws("Unexpected end of content while loading JObject. Path 'foo', line 1, position 6.", () => { JObject.Parse("{ foo:"); @@ -1631,7 +1645,7 @@ Parameter name: arrayIndex" [Test] public void LoadFromNestedObjectIncomplete() { - ExceptionAssert.Throws("Unexpected end of content while loading JObject.", + ExceptionAssert.Throws("Unexpected end of content while loading JObject. Path 'short.error.code', line 6, position 15.", () => { string jsonText = @"{ @@ -1729,7 +1743,7 @@ Parameter name: arrayIndex" [Test] public void ParseAdditionalContent() { - ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: ,. Line 10, position 2.", + ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: ,. Path '', line 10, position 2.", () => { string json = @"{ diff --git a/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs index d0404bf6..fe62f8a4 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JPathTests.cs @@ -59,25 +59,25 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = @"Unexpected character while parsing path indexer: [" -#endif - )] public void BadCharactersInIndexer() { - new JPath("Blah[[0]].Two.Three[1].Four"); + ExceptionAssert.Throws( + @"Unexpected character while parsing path indexer: [", + () => + { + new JPath("Blah[[0]].Two.Three[1].Four"); + }); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = @"Path ended with open indexer. Expected ]" -#endif - )] public void UnclosedIndexer() { - new JPath("Blah[0"); + ExceptionAssert.Throws( + @"Path ended with open indexer. Expected ]", + () => + { + new JPath("Blah[0"); + }); } [Test] @@ -102,25 +102,25 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Empty path indexer." -#endif - )] public void EmptyIndexer() { - new JPath("[]"); + ExceptionAssert.Throws( + "Empty path indexer.", + () => + { + new JPath("[]"); + }); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected character while parsing path: ]" -#endif - )] public void IndexerCloseInProperty() { - new JPath("]"); + ExceptionAssert.Throws( + "Unexpected character while parsing path: ]", + () => + { + new JPath("]"); + }); } [Test] @@ -135,14 +135,14 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Unexpected character following indexer: B" -#endif - )] public void MissingDotAfterIndexer() { - new JPath("[1]Blah"); + ExceptionAssert.Throws( + "Unexpected character following indexer: B", + () => + { + new JPath("[1]Blah"); + }); } [Test] @@ -178,17 +178,17 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = @"Index 1 not valid on JObject." -#endif - )] public void EvaluateIndexerOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); - o.SelectToken("[1]", true); + ExceptionAssert.Throws( + @"Index 1 not valid on JObject.", + () => + { + o.SelectToken("[1]", true); + }); } [Test] @@ -201,43 +201,43 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = @"Property 'BlahBlah' not valid on JArray." -#endif - )] public void EvaluatePropertyOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); - a.SelectToken("BlahBlah", true); + ExceptionAssert.Throws( + @"Property 'BlahBlah' not valid on JArray.", + () => + { + a.SelectToken("BlahBlah", true); + }); } [Test] - [ExpectedException(typeof(IndexOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = @"Index 1 outside the bounds of JConstructor." -#endif - )] public void EvaluateConstructorOutOfBoundsIndxerWithError() { JConstructor c = new JConstructor("Blah"); - c.SelectToken("[1]", true); + ExceptionAssert.Throws( + @"Index 1 outside the bounds of JConstructor.", + () => + { + c.SelectToken("[1]", true); + }); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Property 'Missing' does not exist on JObject." -#endif - )] public void EvaluateMissingPropertyWithError() { JObject o = new JObject( new JProperty("Blah", 1)); - o.SelectToken("Missing", true); + ExceptionAssert.Throws( + "Property 'Missing' does not exist on JObject.", + () => + { + o.SelectToken("Missing", true); + }); } [Test] @@ -250,16 +250,16 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(IndexOutOfRangeException) -#if !NETFX_CORE - , ExpectedMessage = "Index 1000 outside the bounds of JArray." -#endif - )] public void EvaluateArrayOutOfBoundsIndxerWithError() { JArray a = new JArray(1, 2, 3, 4, 5); - a.SelectToken("[1000].Ha", true); + ExceptionAssert.Throws( + "Index 1000 outside the bounds of JArray.", + () => + { + a.SelectToken("[1000].Ha", true); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs index 7cc11dcc..1c82513e 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JPropertyTests.cs @@ -42,15 +42,15 @@ namespace Newtonsoft.Json.Tests.Linq int? index = null; l.ListChanged += (sender, args) => - { - listChangedType = args.ListChangedType; - index = args.NewIndex; - }; + { + listChangedType = args.ListChangedType; + index = args.NewIndex; + }; p.Value = 1; Assert.AreEqual(ListChangedType.ItemChanged, listChangedType.Value); - Assert.AreEqual(0, index.Value); + Assert.AreEqual(0, index.Value); } #endif @@ -64,45 +64,45 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty." -#endif - )] public void IListClear() { JProperty p = new JProperty("TestProperty", null); IList l = p; - l.Clear(); + ExceptionAssert.Throws( + "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.", + () => + { + l.Clear(); + }); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values." -#endif - )] public void IListAdd() { JProperty p = new JProperty("TestProperty", null); IList l = p; - l.Add(null); + ExceptionAssert.Throws( + "Newtonsoft.Json.Linq.JProperty cannot have multiple values.", + () => + { + l.Add(null); + }); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty." -#endif - )] public void IListRemove() { JProperty p = new JProperty("TestProperty", null); IList l = p; - l.Remove(p.Value); + ExceptionAssert.Throws( + "Cannot add or remove items from Newtonsoft.Json.Linq.JProperty.", + () => + { + l.Remove(p.Value); + }); } [Test] @@ -136,25 +136,25 @@ namespace Newtonsoft.Json.Tests.Linq [Test] public void MultiContentConstructor() { - JProperty p = new JProperty("error", new List { "one", "two" }); + JProperty p = new JProperty("error", new List {"one", "two"}); JArray a = (JArray) p.Value; Assert.AreEqual(a.Count, 2); - Assert.AreEqual("one", (string)a[0]); - Assert.AreEqual("two", (string)a[1]); + Assert.AreEqual("one", (string) a[0]); + Assert.AreEqual("two", (string) a[1]); } [Test] - [ExpectedException(typeof(Exception) -#if !NETFX_CORE - , ExpectedMessage = "Newtonsoft.Json.Linq.JProperty cannot have multiple values." -#endif - )] public void IListGenericAdd() { - IList t = new JProperty("error", new List { "one", "two" }); - t.Add(1); - t.Add(2); + IList t = new JProperty("error", new List {"one", "two"}); + + ExceptionAssert.Throws( + "Newtonsoft.Json.Linq.JProperty cannot have multiple values.", + () => + { + t.Add(1); + }); } } -} +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs index 5ecf4e6c..c569965e 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenReaderTest.cs @@ -123,11 +123,6 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Could not convert string to DateTimeOffset: blablahbla. Line 1, position 22." -#endif - )] public void ReadAsDateTimeOffsetBadString() { string json = @"{""Offset"":""blablahbla""}"; @@ -142,15 +137,15 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsDateTimeOffset(); + ExceptionAssert.Throws( + "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22.", + () => + { + reader.ReadAsDateTimeOffset(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading date. Unexpected token: Boolean. Line 1, position 14." -#endif - )] public void ReadAsDateTimeOffsetBoolean() { string json = @"{""Offset"":true}"; @@ -165,7 +160,12 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsDateTimeOffset(); + ExceptionAssert.Throws( + "Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14.", + () => + { + reader.ReadAsDateTimeOffset(); + }); } [Test] @@ -311,26 +311,27 @@ namespace Newtonsoft.Json.Tests.Linq [Test] public void ReadBytesFailure() { - ExceptionAssert.Throws("Error reading bytes. Unexpected token: Integer.", - () => - { - JObject o = - new JObject( - new JProperty("Test1", 1) - ); + ExceptionAssert.Throws( + "Error reading bytes. Unexpected token: Integer. Path 'Test1'.", + () => + { + JObject o = + new JObject( + new JProperty("Test1", 1) + ); - using (JTokenReader jsonReader = new JTokenReader(o)) - { - jsonReader.Read(); - Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); + using (JTokenReader jsonReader = new JTokenReader(o)) + { + jsonReader.Read(); + Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); - jsonReader.Read(); - Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); - Assert.AreEqual("Test1", jsonReader.Value); + jsonReader.Read(); + Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); + Assert.AreEqual("Test1", jsonReader.Value); - jsonReader.ReadAsBytes(); - } - }); + jsonReader.ReadAsBytes(); + } + }); } public class HasBytes @@ -480,11 +481,6 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Could not convert string to integer: hi. Line 1, position 12." -#endif - )] public void ReadAsInt32BadString() { string json = @"{""Name"":""hi""}"; @@ -499,18 +495,15 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsInt32(); - Assert.AreEqual(JsonToken.Integer, reader.TokenType); - Assert.AreEqual(typeof(int), reader.ValueType); - Assert.AreEqual(1, reader.Value); + ExceptionAssert.Throws( + "Could not convert string to integer: hi. Path 'Name', line 1, position 12.", + () => + { + reader.ReadAsInt32(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading integer. Unexpected token: Boolean. Line 1, position 12." -#endif - )] public void ReadAsInt32Boolean() { string json = @"{""Name"":true}"; @@ -525,7 +518,12 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsInt32(); + ExceptionAssert.Throws( + "Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12.", + () => + { + reader.ReadAsInt32(); + }); } [Test] @@ -550,11 +548,6 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Could not convert string to decimal: blah. Line 1, position 14." -#endif - )] public void ReadAsDecimalBadString() { string json = @"{""Name"":""blah""}"; @@ -569,15 +562,15 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsDecimal(); + ExceptionAssert.Throws( + "Could not convert string to decimal: blah. Path 'Name', line 1, position 14.", + () => + { + reader.ReadAsDecimal(); + }); } [Test] - [ExpectedException(typeof(JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = "Error reading decimal. Unexpected token: Boolean. Line 1, position 12." -#endif - )] public void ReadAsDecimalBoolean() { string json = @"{""Name"":true}"; @@ -592,7 +585,12 @@ namespace Newtonsoft.Json.Tests.Linq Assert.IsTrue(reader.Read()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); - reader.ReadAsDecimal(); + ExceptionAssert.Throws( + "Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12.", + () => + { + reader.ReadAsDecimal(); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs index 84f904e2..ac5d9e6f 100644 --- a/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs +++ b/Src/Newtonsoft.Json.Tests/Linq/JTokenTests.cs @@ -565,15 +565,15 @@ namespace Newtonsoft.Json.Tests.Linq } [Test] - [ExpectedException(typeof(ArgumentException) -#if !NETFX_CORE - , ExpectedMessage = "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject." -#endif - )] public void AddValueToObject() { - JObject o = new JObject(); - o.Add(5); + ExceptionAssert.Throws( + "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.", + () => + { + JObject o = new JObject(); + o.Add(5); + }); } [Test] @@ -770,7 +770,7 @@ namespace Newtonsoft.Json.Tests.Linq [Test] public void ParseAdditionalContent() { - ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: ,. Line 5, position 2.", + ExceptionAssert.Throws("Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 2.", () => { string json = @"[ diff --git a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs index 612c9720..fcea2c49 100644 --- a/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json.Tests/Properties/AssemblyInfo.cs @@ -72,5 +72,5 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.0.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.5.3.14818")] +[assembly: AssemblyFileVersion("4.5.3.14821")] #endif diff --git a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs index 7d94cd76..74d20241 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/DynamicTests.cs @@ -188,7 +188,7 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void NoPublicDefaultConstructor() { - ExceptionAssert.Throws("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Line 2, position 18.", + ExceptionAssert.Throws("Unable to find a default constructor to use for type System.Dynamic.DynamicObject. Path 'contributors', line 2, position 18.", () => { var settings = new JsonSerializerSettings(); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 3a907527..afa4ffaf 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -391,14 +391,14 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name." -#endif - )] public void BadJsonPropertyClassSerialize() { - JsonConvert.SerializeObject(new BadJsonPropertyClass()); + ExceptionAssert.Throws( + @"A member with the name 'pie' already exists on 'Newtonsoft.Json.Tests.TestObjects.BadJsonPropertyClass'. Use the JsonPropertyAttribute to specify another name.", + () => + { + JsonConvert.SerializeObject(new BadJsonPropertyClass()); + }); } [Test] @@ -469,16 +469,16 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = @"Bad JSON escape sequence: \j. Line 1, position 7." -#endif - )] public void InvalidBackslash() { string json = @"[""vvv\jvvv""]"; - JsonConvert.DeserializeObject>(json); + ExceptionAssert.Throws( + @"Bad JSON escape sequence: \j. Path '', line 1, position 7.", + () => + { + JsonConvert.DeserializeObject>(json); + }); } [Test] @@ -933,7 +933,7 @@ keyword such as type of business."" Assert.AreEqual(@"{""DefaultConverter"":""\/Date(0)\/"",""MemberConverter"":""1970-01-01T00:00:00Z""}", json); ExceptionAssert.Throws( - "Could not convert string to DateTime: /Date(0)/. Line 1, position 33.", + "Could not convert string to DateTime: /Date(0)/. Path 'DefaultConverter', line 1, position 33.", () => { JsonConvert.DeserializeObject(json, new JsonSerializerSettings @@ -1178,51 +1178,54 @@ keyword such as type of business."" [Test] public void DeserializeRequiredMembersClassNullRequiredValueProperty() { - ExceptionAssert.Throws("Required property 'FirstName' expects a value but got null. Line 6, position 2.", + ExceptionAssert.Throws( + "Required property 'FirstName' expects a value but got null. Path '', line 6, position 2.", () => - { - string json = @"{ + { + string json = @"{ ""FirstName"": null, ""MiddleName"": null, ""LastName"": null, ""BirthDate"": ""\/Date(977309755000)\/"" }"; - JsonConvert.DeserializeObject(json); - }); + JsonConvert.DeserializeObject(json); + }); } [Test] public void SerializeRequiredMembersClassNullRequiredValueProperty() { - ExceptionAssert.Throws("Cannot write a null value for property 'FirstName'. Property requires a value.", - () => - { - RequiredMembersClass requiredMembersClass = new RequiredMembersClass - { - FirstName = null, - BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc), - LastName = null, - MiddleName = null - }; + ExceptionAssert.Throws( + "Cannot write a null value for property 'FirstName'. Property requires a value.", + () => + { + RequiredMembersClass requiredMembersClass = new RequiredMembersClass + { + FirstName = null, + BirthDate = new DateTime(2000, 10, 10, 10, 10, 10, DateTimeKind.Utc), + LastName = null, + MiddleName = null + }; - string json = JsonConvert.SerializeObject(requiredMembersClass); - Console.WriteLine(json); - }); + string json = JsonConvert.SerializeObject(requiredMembersClass); + Console.WriteLine(json); + }); } [Test] public void RequiredMembersClassMissingRequiredProperty() { - ExceptionAssert.Throws("Required property 'LastName' not found in JSON. Line 3, position 2.", - () => - { - string json = @"{ + ExceptionAssert.Throws( + "Required property 'LastName' not found in JSON. Path '', line 3, position 2.", + () => + { + string json = @"{ ""FirstName"": ""Bob"" }"; - JsonConvert.DeserializeObject(json); - }); + JsonConvert.DeserializeObject(json); + }); } [Test] @@ -1301,17 +1304,18 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Line 1, position 14." -#endif - )] public void DeserializeInterfaceProperty() { InterfacePropertyTestClass testClass = new InterfacePropertyTestClass(); testClass.co = new Co(); String strFromTest = JsonConvert.SerializeObject(testClass); - InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass) JsonConvert.DeserializeObject(strFromTest, typeof (InterfacePropertyTestClass)); + + ExceptionAssert.Throws( + @"Could not create an instance of type Newtonsoft.Json.Tests.TestObjects.ICo. Type is an interface or abstract class and cannot be instantated. Path 'co.Name', line 1, position 14.", + () => + { + InterfacePropertyTestClass testFromDe = (InterfacePropertyTestClass) JsonConvert.DeserializeObject(strFromTest, typeof (InterfacePropertyTestClass)); + }); } private Person GetPerson() @@ -1471,13 +1475,19 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof (JsonSerializationException))] public void JsonPropertyWithHandlingValues_ReferenceLoopError() { - JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues(); - o.ReferenceLoopHandlingErrorProperty = o; + string classRef = typeof(JsonPropertyWithHandlingValues).FullName; - JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}); + ExceptionAssert.Throws( + @"Self referencing loop detected for type '" + classRef + "'.", + () => + { + JsonPropertyWithHandlingValues o = new JsonPropertyWithHandlingValues(); + o.ReferenceLoopHandlingErrorProperty = o; + + JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); + }); } [Test] @@ -1957,16 +1967,16 @@ keyword such as type of business."" #endif [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Line 1, position 15." -#endif - )] public void FailWhenClassWithNoDefaultConstructorHasMultipleConstructorsWithArguments() { string json = @"{""sublocation"":""AlertEmailSender.Program.Main"",""userId"":0,""type"":0,""summary"":""Loading settings variables"",""details"":null,""stackTrace"":"" at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n at System.Environment.get_StackTrace()\r\n at mr.Logging.Event..ctor(String summary) in C:\\Projects\\MRUtils\\Logging\\Event.vb:line 71\r\n at AlertEmailSender.Program.Main(String[] args) in C:\\Projects\\AlertEmailSender\\AlertEmailSender\\Program.cs:line 25"",""tag"":null,""time"":""\/Date(1249591032026-0400)\/""}"; - Event e = JsonConvert.DeserializeObject(json); + ExceptionAssert.Throws( + @"Unable to find a constructor to use for type Newtonsoft.Json.Tests.TestObjects.Event. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'sublocation', line 1, position 15.", + () => + { + Event e = JsonConvert.DeserializeObject(json); + }); } [Test] @@ -2001,59 +2011,59 @@ keyword such as type of business."" } [Test] - [ExpectedException(typeof(JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'. -The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. -To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Line 1, position 1." -#endif - )] public void CannotDeserializeArrayIntoObject() { string json = @"[]"; - JsonConvert.DeserializeObject(json); + ExceptionAssert.Throws( + @"Cannot deserialize JSON array (i.e. [1,2,3]) into type 'Newtonsoft.Json.Tests.TestObjects.Person'. +The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. +To force JSON arrays to deserialize add the JsonArrayAttribute to the type. Path '', line 1, position 1.", + () => + { + JsonConvert.DeserializeObject(json); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. -The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List) or a dictionary type (i.e. Dictionary). -To force JSON objects to deserialize add the JsonObjectAttribute to the type. Line 1, position 2." -#endif - )] public void CannotDeserializeObjectIntoArray() { string json = @"{}"; - JsonConvert.DeserializeObject>(json); + ExceptionAssert.Throws( + @"Cannot deserialize JSON object (i.e. {""name"":""value""}) into type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. +The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List) or a dictionary type (i.e. Dictionary). +To force JSON objects to deserialize add the JsonObjectAttribute to the type. Path '', line 1, position 2.", + () => + { + JsonConvert.DeserializeObject>(json); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Line 1, position 1." -#endif - )] public void CannotPopulateArrayIntoObject() { string json = @"[]"; - JsonConvert.PopulateObject(json, new Person()); + ExceptionAssert.Throws( + @"Cannot populate JSON array onto type 'Newtonsoft.Json.Tests.TestObjects.Person'. Path '', line 1, position 1.", + () => + { + JsonConvert.PopulateObject(json, new Person()); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Line 1, position 2." -#endif - )] public void CannotPopulateObjectIntoArray() { string json = @"{}"; - JsonConvert.PopulateObject(json, new List()); + ExceptionAssert.Throws( + @"Cannot populate JSON object onto type 'System.Collections.Generic.List`1[Newtonsoft.Json.Tests.TestObjects.Person]'. Path '', line 1, position 2.", + () => + { + JsonConvert.PopulateObject(json, new List()); + }); } [Test] @@ -2066,79 +2076,79 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'." -#endif - )] public void SerializePropertyGetError() { - JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings - { - ContractResolver = new DefaultContractResolver + ExceptionAssert.Throws( + @"Error getting value from 'ReadTimeout' on 'System.IO.MemoryStream'.", + () => + { + JsonConvert.SerializeObject(new MemoryStream(), new JsonSerializerSettings { + ContractResolver = new DefaultContractResolver + { #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) - IgnoreSerializableAttribute = true + IgnoreSerializableAttribute = true #endif - } - }); - } - - [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'." -#endif - )] - public void DeserializePropertySetError() - { - JsonConvert.DeserializeObject("{ReadTimeout:0}", new JsonSerializerSettings - { - ContractResolver = new DefaultContractResolver - { -#if !(SILVERLIGHT || NETFX_CORE || PORTABLE) - IgnoreSerializableAttribute = true -#endif - } + } + }); }); } [Test] - [ExpectedException(typeof (JsonReaderException) -#if !NETFX_CORE - , ExpectedMessage = @"Could not convert string to integer: . Line 1, position 15." -#endif - )] - public void DeserializeEnsureTypeEmptyStringToIntError() + public void DeserializePropertySetError() { - JsonConvert.DeserializeObject("{ReadTimeout:''}", new JsonSerializerSettings - { - ContractResolver = new DefaultContractResolver + ExceptionAssert.Throws( + @"Error setting value to 'ReadTimeout' on 'System.IO.MemoryStream'.", + () => { + JsonConvert.DeserializeObject("{ReadTimeout:0}", new JsonSerializerSettings + { + ContractResolver = new DefaultContractResolver + { #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) - IgnoreSerializableAttribute = true + IgnoreSerializableAttribute = true #endif - } - }); + } + }); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Error converting value {null} to type 'System.Int32'. Line 1, position 17." + public void DeserializeEnsureTypeEmptyStringToIntError() + { + ExceptionAssert.Throws( + @"Could not convert string to integer: . Path 'ReadTimeout', line 1, position 15.", + () => + { + JsonConvert.DeserializeObject("{ReadTimeout:''}", new JsonSerializerSettings + { + ContractResolver = new DefaultContractResolver + { +#if !(SILVERLIGHT || NETFX_CORE || PORTABLE) + IgnoreSerializableAttribute = true #endif - )] + } + }); + }); + } + + [Test] public void DeserializeEnsureTypeNullToIntError() { - JsonConvert.DeserializeObject("{ReadTimeout:null}", new JsonSerializerSettings - { - ContractResolver = new DefaultContractResolver - { + ExceptionAssert.Throws( + @"Error converting value {null} to type 'System.Int32'. Path 'ReadTimeout', line 1, position 17.", + () => + { + JsonConvert.DeserializeObject("{ReadTimeout:null}", new JsonSerializerSettings + { + ContractResolver = new DefaultContractResolver + { #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) - IgnoreSerializableAttribute = true + IgnoreSerializableAttribute = true #endif - } - }); + } + }); + }); } [Test] @@ -2252,7 +2262,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li [Test] public void DeserializePersonKeyedDictionary() { - ExceptionAssert.Throws("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Line 2, position 46.", + ExceptionAssert.Throws("Could not convert string 'Newtonsoft.Json.Tests.TestObjects.Person' to dictionary key type 'Newtonsoft.Json.Tests.TestObjects.Person'. Create a TypeConverter to convert from the string to the key type object. Path 'Newtonsoft.Json.Tests.TestObjects.Person', line 2, position 46.", () => { string json = @@ -2518,15 +2528,16 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Line 1, position 6." -#endif - )] public void DeserializeDictionaryWithNoDefaultConstructor() { string json = "{key1:'value',key2:'value',key3:'value'}"; - JsonConvert.DeserializeObject(json); + + ExceptionAssert.Throws( + "Unable to find a default constructor to use for type Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+DictionaryWithNoDefaultConstructor. Path 'key1', line 1, position 6.", + () => + { + JsonConvert.DeserializeObject(json); + }); } public class DictionaryWithNoDefaultConstructor : Dictionary @@ -2913,7 +2924,7 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type. Li { ExceptionAssert.Throws( @"Type 'Newtonsoft.Json.Tests.Serialization.JsonSerializerTest+ISerializableTestObject' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data. -To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Line 1, position 14.", +To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true. Path 'booleanValue', line 1, position 14.", () => { JsonTypeReflector.SetFullyTrusted(false); @@ -3608,11 +3619,6 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Line 6, position 11." -#endif - )] public void SerializeRefAdditionalContent() { //Additional text found in JSON string after finishing deserializing object. @@ -3627,13 +3633,20 @@ To fix this error either change the environment to be fully trusted, change the child.Add("Father", reference); var json = JsonConvert.SerializeObject(child, Formatting.Indented); - JsonConvert.DeserializeObject>(json); + + ExceptionAssert.Throws( + "Additional content found in JSON reference object. A JSON reference object should only have a $ref property. Path 'Father.$id', line 6, position 11.", + () => + { + JsonConvert.DeserializeObject>(json); + }); } [Test] public void SerializeRefBadType() { - ExceptionAssert.Throws("JSON reference $ref property must have a string or null value. Line 5, position 14.", + ExceptionAssert.Throws( + "JSON reference $ref property must have a string or null value. Path 'Father.$ref', line 5, position 14.", () => { //Additional text found in JSON string after finishing deserializing object. @@ -4071,9 +4084,10 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (Exception), ExpectedMessage = "Cannot create and populate list type System.Collections.Specialized.StringDictionary.")] public void StringDictionaryTest() { + string classRef = typeof(StringDictionary).FullName; + StringDictionaryTestClass s1 = new StringDictionaryTestClass() { StringDictionaryProperty = new StringDictionary() @@ -4086,7 +4100,12 @@ To fix this error either change the environment to be fully trusted, change the string json = JsonConvert.SerializeObject(s1, Formatting.Indented); - JsonConvert.DeserializeObject(json); + ExceptionAssert.Throws( + "Cannot create and populate list type " + classRef + ".", + () => + { + JsonConvert.DeserializeObject(json); + }); } #endif @@ -4649,14 +4668,14 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "Error converting value {null} to type 'System.DateTime'. Line 1, position 4." -#endif - )] public void DeserializeNullDateTimeValueTest() { - JsonConvert.DeserializeObject("null", typeof (DateTime)); + ExceptionAssert.Throws( + "Error converting value {null} to type 'System.DateTime'. Path '', line 1, position 4.", + () => + { + JsonConvert.DeserializeObject("null", typeof (DateTime)); + }); } [Test] @@ -5360,16 +5379,16 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (Exception) -#if !NETFX_CORE - , ExpectedMessage = "Could not deserialize Null to KeyValuePair." -#endif - )] public void DeserializeNullToNonNullableKeyValuePairArray() { string json = @"[ null ]"; - JsonConvert.DeserializeObject>>>(json); + ExceptionAssert.Throws( + "Cannot convert null value to KeyValuePair. Path '[0]', line 1, position 6.", + () => + { + JsonConvert.DeserializeObject>>>(json); + }); } [Test] @@ -5508,11 +5527,6 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "Error converting value {null} to type 'System.Int32'. Line 5, position 7." -#endif - )] public void DeserializeNullInt() { string json = @"[ @@ -5522,8 +5536,12 @@ To fix this error either change the environment to be fully trusted, change the null ]"; - List numbers = JsonConvert.DeserializeObject>(json); - // JsonSerializationException : Error converting value {null} to type 'System.Int32'. Line 5, position 7. + ExceptionAssert.Throws( + "Error converting value {null} to type 'System.Int32'. Path '[3]', line 5, position 7.", + () => + { + List numbers = JsonConvert.DeserializeObject>(json); + }); } [Test] @@ -5551,29 +5569,31 @@ To fix this error either change the environment to be fully trusted, change the [Test] public void DeserializeBoolInt() { - ExceptionAssert.Throws("Error reading integer. Unexpected token: Boolean. Line 2, position 22.", - () => - { - string json = @"{ + ExceptionAssert.Throws( + "Error reading integer. Unexpected token: Boolean. Path 'PreProperty', line 2, position 22.", + () => + { + string json = @"{ ""PreProperty"": true, ""PostProperty"": ""-1"" }"; - JsonConvert.DeserializeObject(json); - }); + JsonConvert.DeserializeObject(json); + }); } [Test] public void DeserializeUnexpectedEndInt() { - ExceptionAssert.Throws("Unexpected end when setting PreProperty's value. Line 2, position 18.", - () => - { - string json = @"{ + ExceptionAssert.Throws( + "Unexpected end when setting PreProperty's value. Path 'PreProperty', line 2, position 18.", + () => + { + string json = @"{ ""PreProperty"": "; - JsonConvert.DeserializeObject(json); - }); + JsonConvert.DeserializeObject(json); + }); } [Test] @@ -5718,36 +5738,36 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "No JSON content found and type 'System.Double' is not nullable. Line 0, position 0." -#endif - )] public void DeserializeDoubleFromEmptyString() { - JsonConvert.DeserializeObject(""); + ExceptionAssert.Throws( + "No JSON content found and type 'System.Double' is not nullable. Path '', line 0, position 0.", + () => + { + JsonConvert.DeserializeObject(""); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "No JSON content found and type 'System.StringComparison' is not nullable. Line 0, position 0." -#endif - )] public void DeserializeEnumFromEmptyString() { - JsonConvert.DeserializeObject(""); + ExceptionAssert.Throws( + "No JSON content found and type 'System.StringComparison' is not nullable. Path '', line 0, position 0.", + () => + { + JsonConvert.DeserializeObject(""); + }); } [Test] - [ExpectedException(typeof (JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "No JSON content found and type 'System.Int32' is not nullable. Line 0, position 0." -#endif - )] public void DeserializeInt32FromEmptyString() { - JsonConvert.DeserializeObject(""); + ExceptionAssert.Throws( + "No JSON content found and type 'System.Int32' is not nullable. Path '', line 0, position 0.", + () => + { + JsonConvert.DeserializeObject(""); + }); } [Test] @@ -5758,27 +5778,28 @@ To fix this error either change the environment to be fully trusted, change the } [Test] - [ExpectedException(typeof (ArgumentNullException) -#if !NETFX_CORE - , ExpectedMessage = @"Value cannot be null. -Parameter name: value" -#endif - )] public void DeserializeDoubleFromNullString() { - JsonConvert.DeserializeObject(null); + ExceptionAssert.Throws( + @"Value cannot be null. +Parameter name: value", + () => + { + JsonConvert.DeserializeObject(null); + }); } [Test] - [ExpectedException(typeof (ArgumentNullException) -#if !NETFX_CORE - , ExpectedMessage = @"Value cannot be null. -Parameter name: value" -#endif - )] public void DeserializeFromNullString() { - JsonConvert.DeserializeObject(null); + ExceptionAssert.Throws( + @"Value cannot be null. +Parameter name: value", + () => + { + JsonConvert.DeserializeObject(null); + }); + } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs index d082a0cb..6ed5f0cd 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/MissingMemberHandlingTests.cs @@ -41,11 +41,6 @@ namespace Newtonsoft.Json.Tests.Serialization public class MissingMemberHandlingTests : TestFixtureBase { [Test] - [ExpectedException(typeof(JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Could not find member 'Price' on object of type 'ProductShort'. Line 4, position 11." -#endif - )] public void MissingMemberDeserialize() { Product product = new Product(); @@ -67,7 +62,12 @@ namespace Newtonsoft.Json.Tests.Serialization // ] //} - ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); + ExceptionAssert.Throws( + @"Could not find member 'Price' on object of type 'ProductShort'. Path 'Price', line 4, position 11.", + () => + { + ProductShort deserializedProductShort = (ProductShort)JsonConvert.DeserializeObject(output, typeof(ProductShort), new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); + }); } [Test] @@ -126,16 +126,16 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "Could not find member 'Missing' on object of type 'DoubleClass'. Line 1, position 11." -#endif - )] public void MissingMemeber() { string json = @"{""Missing"":1}"; - JsonConvert.DeserializeObject(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); + ExceptionAssert.Throws( + "Could not find member 'Missing' on object of type 'DoubleClass'. Path 'Missing', line 1, position 11.", + () => + { + JsonConvert.DeserializeObject(json, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Error }); + }); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs index ab6e70b0..bdc16d51 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PopulateTests.cs @@ -140,7 +140,7 @@ namespace Newtonsoft.Json.Tests.Serialization [Test] public void PopulateWithBadJson() { - ExceptionAssert.Throws("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Line 1, position 1.", + ExceptionAssert.Throws("Unexpected initial token 'Integer' when populating object. Expected JSON object or array. Path '', line 1, position 1.", () => { JsonConvert.PopulateObject("1", new Person()); diff --git a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs index d5c9af90..eae64b0c 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/PreserveReferencesHandlingTests.cs @@ -94,15 +94,21 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException))] public void SerializeCircularListsError() { + string classRef = typeof(CircularList).FullName; + CircularList circularList = new CircularList(); circularList.Add(null); circularList.Add(new CircularList { null }); circularList.Add(new CircularList { new CircularList { circularList } }); - JsonConvert.SerializeObject(circularList, Formatting.Indented); + ExceptionAssert.Throws( + "Self referencing loop detected for type '" + classRef + "'.", + () => + { + JsonConvert.SerializeObject(circularList, Formatting.Indented); + }); } [Test] @@ -207,11 +213,6 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Cannot preserve reference to array or readonly list: System.String[][]. Line 3, position 15." -#endif - )] public void DeserializeArraysWithPreserveObjectReferences() { string json = @"{ @@ -240,8 +241,13 @@ namespace Newtonsoft.Json.Tests.Serialization ] }"; - JsonConvert.DeserializeObject(json, - new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); + ExceptionAssert.Throws( + @"Cannot preserve reference to array or readonly list: System.String[][]. Path '$values', line 3, position 15.", + () => + { + JsonConvert.DeserializeObject(json, + new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); + }); } public class CircularDictionary : Dictionary @@ -249,14 +255,20 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException))] public void SerializeCircularDictionarysError() { + string classRef = typeof(CircularDictionary).FullName; + CircularDictionary circularDictionary = new CircularDictionary(); - circularDictionary.Add("other", new CircularDictionary { { "blah", null } }); + circularDictionary.Add("other", new CircularDictionary {{"blah", null}}); circularDictionary.Add("self", circularDictionary); - JsonConvert.SerializeObject(circularDictionary, Formatting.Indented); + ExceptionAssert.Throws( + @"Self referencing loop detected for type '" + classRef + "'.", + () => + { + JsonConvert.SerializeObject(circularDictionary, Formatting.Indented); + }); } [Test] @@ -277,18 +289,18 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = @"Unexpected end when deserializing object. Line 2, position 9." -#endif - )] public void UnexpectedEnd() { string json = @"{ ""$id"":"; - JsonConvert.DeserializeObject(json, - new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); + ExceptionAssert.Throws( + @"Unexpected end when deserializing object. Path '$id', line 2, position 9.", + () => + { + JsonConvert.DeserializeObject(json, + new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.All }); + }); } public class CircularReferenceClassConverter : JsonConverter diff --git a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs index d817b4db..05b1f3be 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/SerializationErrorHandlingTests.cs @@ -205,8 +205,8 @@ namespace Newtonsoft.Json.Tests.Serialization #else Assert.AreEqual("[1] - 1 - The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.", errors[0]); #endif - Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray.", errors[1]); - Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime.", errors[2]); + Assert.AreEqual("[2] - 2 - Unexpected token parsing date. Expected String, got StartArray. Path '[2]', line 4, position 10.", errors[1]); + Assert.AreEqual("[4] - 4 - Cannot convert null value to System.DateTime. Path '[4]', line 8, position 13.", errors[2]); } [Test] @@ -294,10 +294,10 @@ namespace Newtonsoft.Json.Tests.Serialization e = ex; } - Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", e.Message); + Assert.AreEqual(@"Could not convert string to DateTime: kjhkjhkjhkjh. Path '[0][0]', line 1, position 16.", e.Message); Assert.AreEqual(1, errors.Count); - Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Line 1, position 16.", errors[0]); + Assert.AreEqual(@"[0][0] - 0 - Could not convert string to DateTime: kjhkjhkjhkjh. Path '[0][0]', line 1, position 16.", errors[0]); } [Test] @@ -314,8 +314,8 @@ namespace Newtonsoft.Json.Tests.Serialization serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof (MyTypeWithRequiredMembers)); Assert.AreEqual(2, errors.Count); - Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Line 1, position 2.", errors[0]); - Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Line 1, position 2.", errors[1]); + Assert.AreEqual(" - Required1 - Required property 'Required1' not found in JSON. Path '', line 1, position 2.", errors[0]); + Assert.AreEqual(" - Required2 - Required property 'Required2' not found in JSON. Path '', line 1, position 2.", errors[1]); } [Test] @@ -335,8 +335,8 @@ namespace Newtonsoft.Json.Tests.Serialization serializer.Deserialize(new JsonTextReader(new StringReader(json)), typeof(int[])); Assert.AreEqual(2, errors.Count); - Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Line 1, position 4.", errors[0]); - Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Line 1, position 8.", errors[1]); + Assert.AreEqual("[0] - 0 - Could not convert string to integer: a. Path '[0]', line 1, position 4.", errors[0]); + Assert.AreEqual("[1] - 1 - Could not convert string to integer: b. Path '[1]', line 1, position 8.", errors[1]); } [Test] diff --git a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs index aac66e94..16dd2745 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.cs @@ -262,10 +262,10 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException))] public void DeserializeWithBadTypeName() { string employeeRef = typeof(EmployeeReference).AssemblyQualifiedName; + string personRef = typeof(Person).AssemblyQualifiedName; string json = @"{ ""$id"": ""1"", @@ -274,11 +274,16 @@ namespace Newtonsoft.Json.Tests.Serialization ""Manager"": null }"; - JsonConvert.DeserializeObject(json, typeof(Person), new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.Objects, - TypeNameAssemblyFormat = FormatterAssemblyStyle.Full - }); + ExceptionAssert.Throws( + @"Type specified in JSON '" + employeeRef + @"' is not compatible with '" + personRef + @"'. Path '$type', line 3, position 143.", + () => + { + JsonConvert.DeserializeObject(json, typeof (Person), new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Objects, + TypeNameAssemblyFormat = FormatterAssemblyStyle.Full + }); + }); } [Test] @@ -302,11 +307,6 @@ namespace Newtonsoft.Json.Tests.Serialization } [Test] - [ExpectedException(typeof(JsonSerializationException) -#if !NETFX_CORE - , ExpectedMessage = "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Line 3, position 56." -#endif - )] public void DeserializeTypeNameOnly() { string json = @"{ @@ -316,10 +316,15 @@ namespace Newtonsoft.Json.Tests.Serialization ""Manager"": null }"; - JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings - { - TypeNameHandling = TypeNameHandling.Objects - }); + ExceptionAssert.Throws( + "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.", + () => + { + JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings + { + TypeNameHandling = TypeNameHandling.Objects + }); + }); } public interface ICorrelatedMessage diff --git a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs index 3b82ab7d..54c8dce8 100644 --- a/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs +++ b/Src/Newtonsoft.Json.Tests/TestFixtureBase.cs @@ -129,7 +129,7 @@ namespace Newtonsoft.Json.Tests catch (TException ex) { if (message != null) - Assert.AreEqual(message, ex.Message); + Assert.AreEqual(message, ex.Message, "Unexpected exception message." + Environment.NewLine + "Expected: " + message + Environment.NewLine + "Got: " + ex.Message); } catch (Exception ex) { diff --git a/Src/Newtonsoft.Json/Bson/BsonObjectId.cs b/Src/Newtonsoft.Json/Bson/BsonObjectId.cs index 0a285631..85cea538 100644 --- a/Src/Newtonsoft.Json/Bson/BsonObjectId.cs +++ b/Src/Newtonsoft.Json/Bson/BsonObjectId.cs @@ -47,7 +47,7 @@ namespace Newtonsoft.Json.Bson { ValidationUtils.ArgumentNotNull(value, "value"); if (value.Length != 12) - throw new Exception("An ObjectId must be 12 bytes"); + throw new ArgumentException("An ObjectId must be 12 bytes", "value"); Value = value; } diff --git a/Src/Newtonsoft.Json/Bson/BsonReader.cs b/Src/Newtonsoft.Json/Bson/BsonReader.cs index f14af3fa..7e39c967 100644 --- a/Src/Newtonsoft.Json/Bson/BsonReader.cs +++ b/Src/Newtonsoft.Json/Bson/BsonReader.cs @@ -269,7 +269,7 @@ namespace Newtonsoft.Json.Bson success = ReadCodeWScope(); break; default: - throw CreateReaderException(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState)); + throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState)); } if (!success) @@ -373,7 +373,7 @@ namespace Newtonsoft.Json.Bson } else { - throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); + throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); } } case State.PostValue: @@ -392,11 +392,11 @@ namespace Newtonsoft.Json.Bson } else { - throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); + throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState); } } default: - throw CreateReaderException(this, "Unexpected state when reading BSON reference: " + CurrentState); + throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState); } } @@ -449,7 +449,7 @@ namespace Newtonsoft.Json.Bson else if (context.Position == lengthMinusEnd) { if (ReadByte() != 0) - throw CreateReaderException(this, "Unexpected end of object byte value."); + throw JsonReaderException.Create(this, "Unexpected end of object byte value."); PopContext(); if (_currentContext != null) @@ -461,7 +461,7 @@ namespace Newtonsoft.Json.Bson } else { - throw CreateReaderException(this, "Read past end of current container context."); + throw JsonReaderException.Create(this, "Read past end of current container context."); } case State.ConstructorStart: break; diff --git a/Src/Newtonsoft.Json/Bson/BsonWriter.cs b/Src/Newtonsoft.Json/Bson/BsonWriter.cs index 6397589c..288042e8 100644 --- a/Src/Newtonsoft.Json/Bson/BsonWriter.cs +++ b/Src/Newtonsoft.Json/Bson/BsonWriter.cs @@ -470,7 +470,7 @@ namespace Newtonsoft.Json.Bson ValidationUtils.ArgumentNotNull(value, "value"); if (value.Length != 12) - throw new Exception("An object id must be 12 bytes"); + throw new ArgumentException("An object id must be 12 bytes", "value"); // hack to update the writer state AutoComplete(JsonToken.Undefined); diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs index 65b8695e..f0ed62eb 100644 --- a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -79,7 +79,7 @@ namespace Newtonsoft.Json.Converters if (value is SqlBinary) return ((SqlBinary) value).Value; - throw new Exception("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType())); + throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType())); } /// @@ -99,7 +99,7 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullable(objectType)) - throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); return null; } @@ -119,7 +119,7 @@ namespace Newtonsoft.Json.Converters } else { - throw new Exception("Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } @@ -131,7 +131,7 @@ namespace Newtonsoft.Json.Converters if (t == typeof(SqlBinary)) return new SqlBinary(data); - throw new Exception("Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType)); } private byte[] ReadByteArray(JsonReader reader) @@ -151,11 +151,11 @@ namespace Newtonsoft.Json.Converters // skip break; default: - throw new Exception("Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } - throw new Exception("Unexpected end when reading bytes."); + throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes."); } /// diff --git a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs index f2f195a8..3d28f20d 100644 --- a/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs +++ b/Src/Newtonsoft.Json/Converters/ExpandoObjectConverter.cs @@ -44,7 +44,7 @@ namespace Newtonsoft.Json.Converters while (reader.TokenType == JsonToken.Comment) { if (!reader.Read()) - throw new Exception("Unexpected end."); + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); } switch (reader.TokenType) @@ -57,7 +57,7 @@ namespace Newtonsoft.Json.Converters if (JsonReader.IsPrimitiveToken(reader.TokenType)) return reader.Value; - throw new Exception("Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } @@ -81,7 +81,7 @@ namespace Newtonsoft.Json.Converters } } - throw new Exception("Unexpected end."); + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); } private object ReadObject(JsonReader reader) @@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Converters string propertyName = reader.Value.ToString(); if (!reader.Read()) - throw new Exception("Unexpected end."); + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); object v = ReadValue(reader); @@ -109,7 +109,7 @@ namespace Newtonsoft.Json.Converters } } - throw new Exception("Unexpected end."); + throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject."); } /// diff --git a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs index 3445d1dc..d67a5977 100644 --- a/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs @@ -78,7 +78,7 @@ namespace Newtonsoft.Json.Converters #endif else { - throw new Exception("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value))); + throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value))); } writer.WriteValue(text); @@ -102,7 +102,7 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) - throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); return null; } @@ -118,7 +118,7 @@ namespace Newtonsoft.Json.Converters } if (reader.TokenType != JsonToken.String) - throw new Exception("Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); string dateText = reader.Value.ToString(); diff --git a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs index 2989a6e1..cadf27b7 100644 --- a/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/JavaScriptDateTimeConverter.cs @@ -35,7 +35,7 @@ namespace Newtonsoft.Json.Converters #endif else { - throw new Exception("Expected date object value."); + throw new JsonSerializationException("Expected date object value."); } writer.WriteStartConstructor("Date"); @@ -60,18 +60,18 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) - throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); return null; } if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) - throw new Exception("Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); + throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); reader.Read(); if (reader.TokenType != JsonToken.Integer) - throw new Exception("Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); long ticks = (long)reader.Value; @@ -80,7 +80,7 @@ namespace Newtonsoft.Json.Converters reader.Read(); if (reader.TokenType != JsonToken.EndConstructor) - throw new Exception("Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected EndConstructor, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); #if !PocketPC && !NET20 if (t == typeof(DateTimeOffset)) diff --git a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index ad35a345..1c0172ee 100644 --- a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -45,7 +45,7 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!isNullable) - throw new Exception("Could not deserialize Null to KeyValuePair."); + throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair."); return null; } diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index d4e32d55..7f0100db 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -110,7 +110,7 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Null) { if (!ReflectionUtils.IsNullableType(objectType)) - throw new Exception("Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType)); return null; } @@ -128,7 +128,7 @@ namespace Newtonsoft.Json.Converters if (reader.TokenType == JsonToken.Integer) return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t); - throw new Exception("Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected token when parsing enum. Expected String or Integer, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } /// @@ -168,7 +168,7 @@ namespace Newtonsoft.Json.Converters string s; if (map.TryGetBySecond(n2, out s)) { - throw new Exception("Enum name '{0}' already exists on enum '{1}'." + throw new InvalidOperationException("Enum name '{0}' already exists on enum '{1}'." .FormatWith(CultureInfo.InvariantCulture, n2, t.Name)); } diff --git a/Src/Newtonsoft.Json/Converters/VersionConverter.cs b/Src/Newtonsoft.Json/Converters/VersionConverter.cs index 8747896a..f4a5b43b 100644 --- a/Src/Newtonsoft.Json/Converters/VersionConverter.cs +++ b/Src/Newtonsoft.Json/Converters/VersionConverter.cs @@ -52,7 +52,7 @@ namespace Newtonsoft.Json.Converters } else { - throw new Exception("Expected Version object value"); + throw new JsonSerializationException("Expected Version object value"); } } @@ -81,12 +81,12 @@ namespace Newtonsoft.Json.Converters } catch (Exception ex) { - throw new Exception("Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex); + throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex); } } else { - throw new Exception("Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); + throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value)); } } } diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index d3d9e488..2bcdeaa1 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -1274,7 +1274,7 @@ namespace Newtonsoft.Json.Converters } else { - throw new Exception("Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } diff --git a/Src/Newtonsoft.Json/JsonArrayAttribute.cs b/Src/Newtonsoft.Json/JsonArrayAttribute.cs index 440c1a9e..7b37275b 100644 --- a/Src/Newtonsoft.Json/JsonArrayAttribute.cs +++ b/Src/Newtonsoft.Json/JsonArrayAttribute.cs @@ -35,6 +35,14 @@ namespace Newtonsoft.Json { private bool _allowNullItems; + // yuck. can't set nullable properties on an attribute in C# + // have to use this approach to get an unset default state + internal NullValueHandling? _itemNullValueHandling; + internal DefaultValueHandling? _itemDefaultValueHandling; + internal ReferenceLoopHandling? _itemReferenceLoopHandling; + internal ObjectCreationHandling? _itemObjectCreationHandling; + internal TypeNameHandling? _itemTypeNameHandling; + /// /// Gets or sets a value indicating whether null items are allowed in the collection. /// @@ -45,6 +53,56 @@ namespace Newtonsoft.Json set { _allowNullItems = value; } } + /// + /// Gets or sets the null value handling used when serializing the collection's items. + /// + /// The null value handling. + public NullValueHandling ItemNullValueHandling + { + get { return _itemNullValueHandling ?? default(NullValueHandling); } + set { _itemNullValueHandling = value; } + } + + /// + /// Gets or sets the default value handling used when serializing the collection's items. + /// + /// The default value handling. + public DefaultValueHandling ItemDefaultValueHandling + { + get { return _itemDefaultValueHandling ?? default(DefaultValueHandling); } + set { _itemDefaultValueHandling = value; } + } + + /// + /// Gets or sets the reference loop handling used when serializing the collection's items. + /// + /// The reference loop handling. + public ReferenceLoopHandling ItemReferenceLoopHandling + { + get { return _itemReferenceLoopHandling ?? default(ReferenceLoopHandling); } + set { _itemReferenceLoopHandling = value; } + } + + /// + /// Gets or sets the object creation handling used when deserializing the collection's items. + /// + /// The object creation handling. + public ObjectCreationHandling ItemObjectCreationHandling + { + get { return _itemObjectCreationHandling ?? default(ObjectCreationHandling); } + set { _itemObjectCreationHandling = value; } + } + + /// + /// Gets or sets the type name handling used when serializing the collection's items. + /// + /// The type name handling. + public TypeNameHandling ItemTypeNameHandling + { + get { return _itemTypeNameHandling ?? default(TypeNameHandling); } + set { _itemTypeNameHandling = value; } + } + /// /// Initializes a new instance of the class. /// diff --git a/Src/Newtonsoft.Json/JsonConverterAttribute.cs b/Src/Newtonsoft.Json/JsonConverterAttribute.cs index b9efff85..bea9a4ac 100644 --- a/Src/Newtonsoft.Json/JsonConverterAttribute.cs +++ b/Src/Newtonsoft.Json/JsonConverterAttribute.cs @@ -41,7 +41,7 @@ namespace Newtonsoft.Json } catch (Exception ex) { - throw new Exception("Error creating {0}".FormatWith(CultureInfo.InvariantCulture, converterType), ex); + throw new JsonException("Error creating {0}".FormatWith(CultureInfo.InvariantCulture, converterType), ex); } } } diff --git a/Src/Newtonsoft.Json/JsonException.cs b/Src/Newtonsoft.Json/JsonException.cs new file mode 100644 index 00000000..cb80e270 --- /dev/null +++ b/Src/Newtonsoft.Json/JsonException.cs @@ -0,0 +1,83 @@ +#region License +// Copyright (c) 2007 James Newton-King +// +// Permission is hereby granted, free of charge, to any person +// obtaining a copy of this software and associated documentation +// files (the "Software"), to deal in the Software without +// restriction, including without limitation the rights to use, +// copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following +// conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +#endregion + +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Text; + +namespace Newtonsoft.Json +{ + /// + /// The exception thrown when an error occurs during Json serialization or deserialization. + /// +#if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) + [Serializable] +#endif + public class JsonException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public JsonException() + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message. + /// + /// The error message that explains the reason for the exception. + public JsonException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class + /// with a specified error message and a reference to the inner exception that is the cause of this exception. + /// + /// The error message that explains the reason for the exception. + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified. + public JsonException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE || PORTABLE) + /// + /// Initializes a new instance of the class. + /// + /// The that holds the serialized object data about the exception being thrown. + /// The that contains contextual information about the source or destination. + /// The parameter is null. + /// The class name is null or is zero (0). + public JsonException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } +#endif + } +} \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonReader.cs b/Src/Newtonsoft.Json/JsonReader.cs index 1a4a2e75..211658a6 100644 --- a/Src/Newtonsoft.Json/JsonReader.cs +++ b/Src/Newtonsoft.Json/JsonReader.cs @@ -273,7 +273,7 @@ namespace Newtonsoft.Json if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; - throw CreateReaderException(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); + throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } @@ -388,14 +388,14 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); + throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (TokenType == JsonToken.EndArray) return null; - throw CreateReaderException(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } #endif @@ -453,17 +453,17 @@ namespace Newtonsoft.Json // skip break; default: - throw CreateReaderException(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } } - throw CreateReaderException(this, "Unexpected end when reading bytes."); + throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); } if (TokenType == JsonToken.EndArray) return null; - throw CreateReaderException(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal decimal? ReadAsDecimalInternal() @@ -500,14 +500,14 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); + throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (TokenType == JsonToken.EndArray) return null; - throw CreateReaderException(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal int? ReadAsInt32Internal() @@ -544,14 +544,14 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); + throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (TokenType == JsonToken.EndArray) return null; - throw CreateReaderException(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal string ReadAsStringInternal() @@ -593,7 +593,7 @@ namespace Newtonsoft.Json if (TokenType == JsonToken.EndArray) return null; - throw CreateReaderException(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal DateTime? ReadAsDateTimeInternal() @@ -633,14 +633,14 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); + throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, Value)); } } if (TokenType == JsonToken.EndArray) return null; - throw CreateReaderException(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); + throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } private bool IsWrappedInTypeObject() @@ -650,7 +650,7 @@ namespace Newtonsoft.Json if (TokenType == JsonToken.StartObject) { if (!ReadInternal()) - throw CreateReaderException(this, "Unexpected end when reading bytes."); + throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); if (Value.ToString() == "$type") { @@ -665,7 +665,7 @@ namespace Newtonsoft.Json } } - throw CreateReaderException(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); + throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } return false; @@ -771,7 +771,7 @@ namespace Newtonsoft.Json JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) - throw CreateReaderException(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); + throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); _currentState = (Peek() != JsonContainerType.None) ? State.PostValue : State.Finished; } @@ -798,7 +798,7 @@ namespace Newtonsoft.Json _currentState = State.Finished; break; default: - throw CreateReaderException(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); + throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } @@ -844,7 +844,7 @@ namespace Newtonsoft.Json case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: - throw CreateReaderException(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); + throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } @@ -875,46 +875,5 @@ namespace Newtonsoft.Json _tokenType = JsonToken.None; _value = null; } - - internal JsonReaderException CreateReaderException(JsonReader reader, string message) - { - return CreateReaderException(reader, message, null); - } - - internal JsonReaderException CreateReaderException(JsonReader reader, string message, Exception ex) - { - return CreateReaderException(reader as IJsonLineInfo, message, ex); - } - - internal JsonReaderException CreateReaderException(IJsonLineInfo lineInfo, string message, Exception ex) - { - message = FormatExceptionMessage(lineInfo, message); - - int lineNumber; - int linePosition; - if (lineInfo != null && lineInfo.HasLineInfo()) - { - lineNumber = lineInfo.LineNumber; - linePosition = lineInfo.LinePosition; - } - else - { - lineNumber = 0; - linePosition = 0; - } - - return new JsonReaderException(message, ex, Path, lineNumber, linePosition); - } - - internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string message) - { - if (!message.EndsWith(".")) - message += "."; - - if (lineInfo != null && lineInfo.HasLineInfo()) - message += " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); - - return message; - } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonReaderException.cs b/Src/Newtonsoft.Json/JsonReaderException.cs index 946a4351..ac0fbcf7 100644 --- a/Src/Newtonsoft.Json/JsonReaderException.cs +++ b/Src/Newtonsoft.Json/JsonReaderException.cs @@ -24,7 +24,9 @@ #endregion using System; +using System.Globalization; using System.Runtime.Serialization; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json { @@ -34,7 +36,7 @@ namespace Newtonsoft.Json #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) [Serializable] #endif - public class JsonReaderException : Exception + public class JsonReaderException : JsonException { /// /// Gets the line number indicating where the error occurred. @@ -104,5 +106,52 @@ namespace Newtonsoft.Json LineNumber = lineNumber; LinePosition = linePosition; } + + internal static JsonReaderException Create(JsonReader reader, string message) + { + return Create(reader, message, null); + } + + internal static JsonReaderException Create(JsonReader reader, string message, Exception ex) + { + return Create(reader as IJsonLineInfo, reader.Path, message, ex); + } + + internal static JsonReaderException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + { + message = FormatExceptionMessage(lineInfo, path, message); + + int lineNumber; + int linePosition; + if (lineInfo != null && lineInfo.HasLineInfo()) + { + lineNumber = lineInfo.LineNumber; + linePosition = lineInfo.LinePosition; + } + else + { + lineNumber = 0; + linePosition = 0; + } + + return new JsonReaderException(message, ex, path, lineNumber, linePosition); + } + + internal static string FormatExceptionMessage(IJsonLineInfo lineInfo, string path, string message) + { + message = message.Trim(); + + if (!message.EndsWith(".")) + message += "."; + + message += " Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path); + + if (lineInfo != null && lineInfo.HasLineInfo()) + message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition); + + message += "."; + + return message; + } } } diff --git a/Src/Newtonsoft.Json/JsonSerializationException.cs b/Src/Newtonsoft.Json/JsonSerializationException.cs index b0978408..843988a4 100644 --- a/Src/Newtonsoft.Json/JsonSerializationException.cs +++ b/Src/Newtonsoft.Json/JsonSerializationException.cs @@ -36,7 +36,7 @@ namespace Newtonsoft.Json #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) [Serializable] #endif - public class JsonSerializationException : Exception + public class JsonSerializationException : JsonException { /// /// Initializes a new instance of the class. @@ -79,5 +79,22 @@ namespace Newtonsoft.Json { } #endif + + internal static JsonSerializationException Create(JsonReader reader, string message) + { + return Create(reader, message, null); + } + + internal static JsonSerializationException Create(JsonReader reader, string message, Exception ex) + { + return Create(reader as IJsonLineInfo, reader.Path, message, ex); + } + + internal static JsonSerializationException Create(IJsonLineInfo lineInfo, string path, string message, Exception ex) + { + message = JsonReaderException.FormatExceptionMessage(lineInfo, path, message); + + return new JsonSerializationException(message, ex); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/JsonTextReader.cs b/Src/Newtonsoft.Json/JsonTextReader.cs index 8ac6a831..49f8a2c6 100644 --- a/Src/Newtonsoft.Json/JsonTextReader.cs +++ b/Src/Newtonsoft.Json/JsonTextReader.cs @@ -501,7 +501,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } } return false; @@ -510,7 +510,7 @@ namespace Newtonsoft.Json case State.Error: break; default: - throw CreateReaderException(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); + throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState)); } } } @@ -534,7 +534,7 @@ namespace Newtonsoft.Json if (ReadData(true) == 0) { _charPos = charPos; - throw CreateReaderException(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); + throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } } break; @@ -543,7 +543,7 @@ namespace Newtonsoft.Json if (!EnsureChars(0, true)) { _charPos = charPos; - throw CreateReaderException(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); + throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote)); } // start of escape sequence @@ -648,7 +648,7 @@ namespace Newtonsoft.Json default: charPos++; _charPos = charPos; - throw CreateReaderException(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); + throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar)); } if (buffer == null) @@ -721,7 +721,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Unexpected end while parsing unicode character."); + throw JsonReaderException.Create(this, "Unexpected end while parsing unicode character."); } return writeChar; } @@ -848,7 +848,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } break; } @@ -927,7 +927,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } string propertyName = _stringReference.ToString(); @@ -935,7 +935,7 @@ namespace Newtonsoft.Json EatWhitespace(false); if (_chars[_charPos] != ':') - throw CreateReaderException(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; @@ -964,7 +964,7 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) - throw CreateReaderException(this, "Unexpected end while parsing unquoted property name."); + throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name."); break; } @@ -985,7 +985,7 @@ namespace Newtonsoft.Json return; } - throw CreateReaderException(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + throw JsonReaderException.Create(this, "Invalid JavaScript property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } @@ -1029,11 +1029,11 @@ namespace Newtonsoft.Json else if (next == 'e') ParseConstructor(); else - throw CreateReaderException(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); } else { - throw CreateReaderException(this, "Unexpected end."); + throw JsonReaderException.Create(this, "Unexpected end."); } return true; case 'N': @@ -1100,7 +1100,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + throw JsonReaderException.Create(this, "Unexpected character encountered while parsing value: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } } @@ -1183,7 +1183,7 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) - throw CreateReaderException(this, "Unexpected end while parsing constructor."); + throw JsonReaderException.Create(this, "Unexpected end while parsing constructor."); } else { @@ -1221,7 +1221,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); + throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar)); } } @@ -1231,7 +1231,7 @@ namespace Newtonsoft.Json EatWhitespace(false); if (_chars[_charPos] != '(') - throw CreateReaderException(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); _charPos++; @@ -1350,7 +1350,7 @@ namespace Newtonsoft.Json } catch (OverflowException ex) { - throw CreateReaderException((JsonReader)this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex); + throw JsonReaderException.Create((JsonReader)this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, number), ex); } numberType = JsonToken.Integer; @@ -1369,7 +1369,7 @@ namespace Newtonsoft.Json _charPos++; if (!EnsureChars(1, false) || _chars[_charPos] != '*') - throw CreateReaderException(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); + throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos])); else _charPos++; @@ -1385,7 +1385,7 @@ namespace Newtonsoft.Json if (_charsUsed == _charPos) { if (ReadData(true) == 0) - throw CreateReaderException(this, "Unexpected end while parsing comment."); + throw JsonReaderException.Create(this, "Unexpected end while parsing comment."); } else { @@ -1498,7 +1498,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing boolean value."); + throw JsonReaderException.Create(this, "Error parsing boolean value."); } } @@ -1510,7 +1510,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing null value."); + throw JsonReaderException.Create(this, "Error parsing null value."); } } @@ -1522,7 +1522,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing undefined value."); + throw JsonReaderException.Create(this, "Error parsing undefined value."); } } @@ -1534,7 +1534,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing boolean value."); + throw JsonReaderException.Create(this, "Error parsing boolean value."); } } @@ -1546,7 +1546,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing negative infinity value."); + throw JsonReaderException.Create(this, "Error parsing negative infinity value."); } } @@ -1558,7 +1558,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing positive infinity value."); + throw JsonReaderException.Create(this, "Error parsing positive infinity value."); } } @@ -1570,7 +1570,7 @@ namespace Newtonsoft.Json } else { - throw CreateReaderException(this, "Error parsing NaN value."); + throw JsonReaderException.Create(this, "Error parsing NaN value."); } } diff --git a/Src/Newtonsoft.Json/JsonValidatingReader.cs b/Src/Newtonsoft.Json/JsonValidatingReader.cs index 0e6f73e1..f65fb96d 100644 --- a/Src/Newtonsoft.Json/JsonValidatingReader.cs +++ b/Src/Newtonsoft.Json/JsonValidatingReader.cs @@ -188,7 +188,7 @@ namespace Newtonsoft.Json case JTokenType.Object: { if (_currentScope.CurrentPropertyName == null) - throw new Exception("CurrentPropertyName has not been set on scope."); + throw new JsonReaderException("CurrentPropertyName has not been set on scope."); IList schemas = new List(); @@ -291,7 +291,7 @@ namespace Newtonsoft.Json set { if (TokenType != JsonToken.None) - throw new Exception("Cannot change schema while validating JSON."); + throw new InvalidOperationException("Cannot change schema while validating JSON."); _schema = value; _model = null; diff --git a/Src/Newtonsoft.Json/JsonWriterException.cs b/Src/Newtonsoft.Json/JsonWriterException.cs index 9dc8c440..4cea3380 100644 --- a/Src/Newtonsoft.Json/JsonWriterException.cs +++ b/Src/Newtonsoft.Json/JsonWriterException.cs @@ -36,7 +36,7 @@ namespace Newtonsoft.Json #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) [Serializable] #endif - public class JsonWriterException : Exception + public class JsonWriterException : JsonException { /// /// Initializes a new instance of the class. diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs index 6851ea88..997157a7 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -111,10 +111,10 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) - throw new Exception("Error reading JArray from JsonReader."); + throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader."); } if (reader.TokenType != JsonToken.StartArray) - throw new Exception("Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonReaderException.Create(reader, "Error reading JArray from JsonReader. Current JsonReader item is not an array: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JArray a = new JArray(); a.SetLineInfo(reader as IJsonLineInfo); @@ -131,12 +131,12 @@ namespace Newtonsoft.Json.Linq /// A populated from the string that contains JSON. public static new JArray Parse(string json) { - JsonReader jsonReader = new JsonTextReader(new StringReader(json)); + JsonReader reader = new JsonTextReader(new StringReader(json)); - JArray a = Load(jsonReader); + JArray a = Load(reader); - if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) - throw new Exception("Additional text found in JSON string after parsing content."); + if (reader.Read() && reader.TokenType != JsonToken.Comment) + throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); return a; } diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index 679f74b1..fe17fc6d 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -184,11 +184,11 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) - throw new Exception("Error reading JConstructor from JsonReader."); + throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader."); } if (reader.TokenType != JsonToken.StartConstructor) - throw new Exception("Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonReaderException.Create(reader, "Error reading JConstructor from JsonReader. Current JsonReader item is not a constructor: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JConstructor c = new JConstructor((string)reader.Value); c.SetLineInfo(reader as IJsonLineInfo); diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index eae6718c..f106e855 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -589,19 +589,19 @@ namespace Newtonsoft.Json.Linq ClearItems(); } - internal void ReadTokenFrom(JsonReader r) + internal void ReadTokenFrom(JsonReader reader) { - int startDepth = r.Depth; + int startDepth = reader.Depth; - if (!r.Read()) - throw new Exception("Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + if (!reader.Read()) + throw JsonReaderException.Create(reader, "Error reading {0} from JsonReader.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); - ReadContentFrom(r); + ReadContentFrom(reader); - int endDepth = r.Depth; + int endDepth = reader.Depth; if (endDepth > startDepth) - throw new Exception("Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); + throw JsonReaderException.Create(reader, "Unexpected end of content while loading {0}.".FormatWith(CultureInfo.InvariantCulture, GetType().Name)); } internal void ReadContentFrom(JsonReader r) @@ -908,10 +908,10 @@ namespace Newtonsoft.Json.Linq OnAddingNew(args); if (args.NewObject == null) - throw new Exception("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType())); + throw new JsonException("Could not determine new value to add to '{0}'.".FormatWith(CultureInfo.InvariantCulture, GetType())); if (!(args.NewObject is JToken)) - throw new Exception("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof (JToken))); + throw new JsonException("New item to be added to collection must be compatible with {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JToken))); JToken newItem = (JToken)args.NewObject; Add(newItem); diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index 4bc1c10a..c0316c46 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -289,14 +289,12 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) - throw new Exception("Error reading JObject from JsonReader."); + throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); } if (reader.TokenType != JsonToken.StartObject) { - throw new Exception( - "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith( - CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JObject o = new JObject(); @@ -314,12 +312,12 @@ namespace Newtonsoft.Json.Linq /// A populated from the string that contains JSON. public static new JObject Parse(string json) { - JsonReader jsonReader = new JsonTextReader(new StringReader(json)); + JsonReader reader = new JsonTextReader(new StringReader(json)); - JObject o = Load(jsonReader); + JObject o = Load(reader); - if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) - throw new Exception("Additional text found in JSON string after parsing content."); + if (reader.Read() && reader.TokenType != JsonToken.Comment) + throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); return o; } diff --git a/Src/Newtonsoft.Json/Linq/JPath.cs b/Src/Newtonsoft.Json/Linq/JPath.cs index 5a90db2c..9fd7eda9 100644 --- a/Src/Newtonsoft.Json/Linq/JPath.cs +++ b/Src/Newtonsoft.Json/Linq/JPath.cs @@ -46,7 +46,7 @@ namespace Newtonsoft.Json.Linq break; case ']': case ')': - throw new Exception("Unexpected character while parsing path: " + currentChar); + throw new JsonException("Unexpected character while parsing path: " + currentChar); case '.': if (_currentIndex > currentPartStartIndex) { @@ -58,7 +58,7 @@ namespace Newtonsoft.Json.Linq break; default: if (followingIndexer) - throw new Exception("Unexpected character following indexer: " + currentChar); + throw new JsonException("Unexpected character following indexer: " + currentChar); break; } @@ -95,17 +95,17 @@ namespace Newtonsoft.Json.Linq } else { - throw new Exception("Unexpected character while parsing path indexer: " + currentCharacter); + throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter); } _currentIndex++; } if (!indexerClosed) - throw new Exception("Path ended with open indexer. Expected " + indexerCloseChar); + throw new JsonException("Path ended with open indexer. Expected " + indexerCloseChar); if (indexerLength == 0) - throw new Exception("Empty path indexer."); + throw new JsonException("Empty path indexer."); string indexer = _expression.Substring(indexerStart, indexerLength); Parts.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture)); @@ -126,12 +126,12 @@ namespace Newtonsoft.Json.Linq current = o[propertyName]; if (current == null && errorWhenNoMatch) - throw new Exception("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + throw new JsonException("Property '{0}' does not exist on JObject.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } else { if (errorWhenNoMatch) - throw new Exception("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name)); + throw new JsonException("Property '{0}' not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, propertyName, current.GetType().Name)); return null; } @@ -170,7 +170,7 @@ namespace Newtonsoft.Json.Linq else { if (errorWhenNoMatch) - throw new Exception("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name)); + throw new JsonException("Index {0} not valid on {1}.".FormatWith(CultureInfo.InvariantCulture, index, current.GetType().Name)); return null; } diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index f838606f..63c4ca50 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -120,18 +120,18 @@ namespace Newtonsoft.Json.Linq internal override bool RemoveItem(JToken item) { - throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void RemoveItemAt(int index) { - throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override void InsertItem(int index, JToken item, bool skipParentCheck) { if (Value != null) - throw new Exception("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + throw new JsonException("{0} cannot have multiple values.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); base.InsertItem(0, item, false); } @@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Linq internal override void ClearItems() { - throw new Exception("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); + throw new JsonException("Cannot add or remove items from {0}.".FormatWith(CultureInfo.InvariantCulture, typeof(JProperty))); } internal override bool DeepEquals(JToken node) @@ -227,12 +227,10 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) - throw new Exception("Error reading JProperty from JsonReader."); + throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader."); } if (reader.TokenType != JsonToken.PropertyName) - throw new Exception( - "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith( - CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonReaderException.Create(reader, "Error reading JProperty from JsonReader. Current JsonReader item is not a property: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); JProperty p = new JProperty((string)reader.Value); p.SetLineInfo(reader as IJsonLineInfo); diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index e39780b4..77f85bf2 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -1204,7 +1204,7 @@ namespace Newtonsoft.Json.Linq if (reader.TokenType == JsonToken.None) { if (!reader.Read()) - throw new Exception("Error reading JToken from JsonReader."); + throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader."); } if (reader.TokenType == JsonToken.StartObject) @@ -1223,7 +1223,7 @@ namespace Newtonsoft.Json.Linq return new JValue(reader.Value); // TODO: loading constructor and parameters? - throw new Exception("Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonReaderException.Create(reader, "Error reading JToken from JsonReader. Unexpected token: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } /// @@ -1233,12 +1233,12 @@ namespace Newtonsoft.Json.Linq /// A populated from the string that contains JSON. public static JToken Parse(string json) { - JsonReader jsonReader = new JsonTextReader(new StringReader(json)); + JsonReader reader = new JsonTextReader(new StringReader(json)); - JToken t = Load(jsonReader); + JToken t = Load(reader); - if (jsonReader.Read() && jsonReader.TokenType != JsonToken.Comment) - throw new Exception("Additional text found in JSON string after parsing content."); + if (reader.Read() && reader.TokenType != JsonToken.Comment) + throw JsonReaderException.Create(reader, "Additional text found in JSON string after parsing content."); return t; } diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj index f7faaf34..f08af6ca 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net20.csproj @@ -98,6 +98,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj index 440ee79e..79ac86f7 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Net35.csproj @@ -110,6 +110,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj index 35bd7b32..884c7ac7 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.Silverlight.csproj @@ -117,6 +117,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj index 13bab127..ac2890b4 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.WindowsPhone.csproj @@ -90,6 +90,7 @@ + diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index 760ae37d..43b7c101 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -103,6 +103,7 @@ + diff --git a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs index 98899305..3c97661d 100644 --- a/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs +++ b/Src/Newtonsoft.Json/Properties/AssemblyInfo.cs @@ -91,7 +91,7 @@ using System.Security; // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.0.0")] #if !PocketPC -[assembly: AssemblyFileVersion("4.5.3.14818")] +[assembly: AssemblyFileVersion("4.5.3.14821")] #endif [assembly: CLSCompliant(true)] diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs index 52a53f20..1229a1fa 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaBuilder.cs @@ -83,7 +83,7 @@ namespace Newtonsoft.Json.Schema private JsonSchema BuildSchema() { if (_reader.TokenType != JsonToken.StartObject) - throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); _reader.Read(); // empty schema object @@ -105,13 +105,12 @@ namespace Newtonsoft.Json.Schema while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { if (_reader.TokenType == JsonToken.StartObject) - throw new Exception("Found StartObject within the schema reference with the Id '{0}'" - .FormatWith(CultureInfo.InvariantCulture, id)); + throw JsonReaderException.Create(_reader, "Found StartObject within the schema reference with the Id '{0}'".FormatWith(CultureInfo.InvariantCulture, id)); } JsonSchema referencedSchema = _resolver.GetSchema(id); if (referencedSchema == null) - throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id)); + throw new JsonException("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id)); return referencedSchema; } @@ -237,7 +236,7 @@ namespace Newtonsoft.Json.Schema private void ProcessEnum() { if (_reader.TokenType != JsonToken.StartArray) - throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); CurrentSchema.Enum = new List(); @@ -258,7 +257,7 @@ namespace Newtonsoft.Json.Schema while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.StartObject) - throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); string label = null; JToken value = null; @@ -277,21 +276,21 @@ namespace Newtonsoft.Json.Schema label = (string) _reader.Value; break; default: - throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + throw JsonReaderException.Create(_reader, "Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName)); } } if (value == null) - throw new Exception("No value specified for JSON schema option."); + throw new JsonException("No value specified for JSON schema option."); if (CurrentSchema.Options.ContainsKey(value)) - throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value)); + throw new JsonException("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value)); CurrentSchema.Options.Add(value, label); } break; default: - throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } @@ -313,13 +312,13 @@ namespace Newtonsoft.Json.Schema while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.String) - throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); CurrentSchema.Identity.Add(_reader.Value.ToString()); } break; default: - throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } @@ -336,7 +335,7 @@ namespace Newtonsoft.Json.Schema Dictionary patternProperties = new Dictionary(); if (_reader.TokenType != JsonToken.StartObject) - throw new Exception("Expected start object token."); + throw JsonReaderException.Create(_reader, "Expected StartObject token."); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { @@ -344,7 +343,7 @@ namespace Newtonsoft.Json.Schema _reader.Read(); if (patternProperties.ContainsKey(propertyName)) - throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); patternProperties.Add(propertyName, BuildSchema()); } @@ -368,7 +367,7 @@ namespace Newtonsoft.Json.Schema } break; default: - throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } @@ -377,7 +376,7 @@ namespace Newtonsoft.Json.Schema IDictionary properties = new Dictionary(); if (_reader.TokenType != JsonToken.StartObject) - throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); while (_reader.Read() && _reader.TokenType != JsonToken.EndObject) { @@ -385,7 +384,7 @@ namespace Newtonsoft.Json.Schema _reader.Read(); if (properties.ContainsKey(propertyName)) - throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); + throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName)); properties.Add(propertyName, BuildSchema()); } @@ -406,14 +405,14 @@ namespace Newtonsoft.Json.Schema while (_reader.Read() && _reader.TokenType != JsonToken.EndArray) { if (_reader.TokenType != JsonToken.String) - throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); type = type | MapType(_reader.Value.ToString()); } return type; default: - throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); + throw JsonReaderException.Create(_reader, "Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType)); } } @@ -421,7 +420,7 @@ namespace Newtonsoft.Json.Schema { JsonSchemaType mappedType; if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType)) - throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); + throw new JsonException("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type)); return mappedType; } diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs index afafffa4..3fc70a5f 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaException.cs @@ -34,7 +34,7 @@ namespace Newtonsoft.Json.Schema #if !(SILVERLIGHT || WINDOWS_PHONE || NETFX_CORE || PORTABLE) [Serializable] #endif - public class JsonSchemaException : Exception + public class JsonSchemaException : JsonException { /// /// Gets the line number indicating where the error occurred. diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index cf4f6d79..306b6379 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -238,7 +238,7 @@ namespace Newtonsoft.Json.Schema // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { - throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); + throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); @@ -344,7 +344,7 @@ namespace Newtonsoft.Json.Schema CurrentSchema.Type = JsonSchemaType.Any; break; default: - throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); + throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } } @@ -457,7 +457,7 @@ namespace Newtonsoft.Json.Schema case TypeCode.String: return schemaType | JsonSchemaType.String; default: - throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); + throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } } } diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index fb23cdea..69a5eed7 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -385,7 +385,7 @@ namespace Newtonsoft.Json.Serialization IList markedConstructors = objectType.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(c => c.IsDefined(typeof(JsonConstructorAttribute), true)).ToList(); if (markedConstructors.Count > 1) - throw new Exception("Multiple constructors with the JsonConstructorAttribute."); + throw new JsonException("Multiple constructors with the JsonConstructorAttribute."); else if (markedConstructors.Count == 1) return markedConstructors[0]; @@ -792,26 +792,26 @@ namespace Newtonsoft.Json.Serialization return false; if (currentCallback != null) - throw new Exception("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); + throw new JsonException("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, method, currentCallback, GetClrTypeFullName(method.DeclaringType), attributeType)); if (prevAttributeType != null) - throw new Exception("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); + throw new JsonException("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, prevAttributeType, attributeType, GetClrTypeFullName(method.DeclaringType), method)); if (method.IsVirtual) - throw new Exception("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); + throw new JsonException("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, method, GetClrTypeFullName(method.DeclaringType), attributeType)); if (method.ReturnType != typeof(void)) - throw new Exception("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); + throw new JsonException("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method)); if (attributeType == typeof(OnErrorAttribute)) { if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext)) - throw new Exception("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext))); + throw new JsonException("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext), typeof(ErrorContext))); } else { if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext)) - throw new Exception("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext))); + throw new JsonException("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, GetClrTypeFullName(method.DeclaringType), method, typeof(StreamingContext))); } prevAttributeType = attributeType; diff --git a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs index 12e93eb6..02bb1893 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultReferenceResolver.cs @@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Serialization else if (context is JsonSerializerProxy) internalSerializer = ((JsonSerializerProxy) context).GetInternalSerializer(); else - throw new Exception("The DefaultReferenceResolver can only be used internally."); + throw new JsonException("The DefaultReferenceResolver can only be used internally."); return internalSerializer.DefaultReferenceMappings; } diff --git a/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs b/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs index 7bedb5c6..dcb83e05 100644 --- a/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs +++ b/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs @@ -73,11 +73,11 @@ namespace Newtonsoft.Json.Serialization if (value == null) { if (!ReflectionUtils.IsNullable(ReflectionUtils.GetMemberUnderlyingType(_memberInfo))) - throw new Exception("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); + throw new JsonSerializationException("Incompatible value. Cannot set {0} to null.".FormatWith(CultureInfo.InvariantCulture, _memberInfo)); } else if (!ReflectionUtils.GetMemberUnderlyingType(_memberInfo).IsAssignableFrom(value.GetType())) { - throw new Exception("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType())); + throw new JsonSerializationException("Incompatible value. Cannot set {0} to type {1}.".FormatWith(CultureInfo.InvariantCulture, _memberInfo, value.GetType())); } #endif diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 543fc243..835d5681 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -71,7 +71,7 @@ namespace Newtonsoft.Json.Serialization if (contract.ContractType == JsonContractType.Array) PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, (JsonArrayContract) contract); else - throw CreateSerializationException(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } else if (reader.TokenType == JsonToken.StartObject) { @@ -90,11 +90,11 @@ namespace Newtonsoft.Json.Serialization else if (contract.ContractType == JsonContractType.Object) PopulateObject(target, reader, (JsonObjectContract) contract, id); else - throw CreateSerializationException(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); } else { - throw CreateSerializationException(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); + throw JsonSerializationException.Create(reader, "Unexpected initial token '{0}' when populating object. Expected JSON object or array.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } } @@ -118,7 +118,7 @@ namespace Newtonsoft.Json.Serialization if (reader.TokenType == JsonToken.None && !ReadForType(reader, contract, converter != null, false)) { if (contract != null && !contract.IsNullable) - throw CreateSerializationException(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "No JSON content found and type '{0}' is not nullable.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); return null; } @@ -280,28 +280,11 @@ namespace Newtonsoft.Json.Serialization // ignore break; default: - throw CreateSerializationException(reader, "Unexpected token while deserializing object: " + reader.TokenType); + throw JsonSerializationException.Create(reader, "Unexpected token while deserializing object: " + reader.TokenType); } } while (reader.Read()); - throw CreateSerializationException(reader, "Unexpected end when deserializing object."); - } - - private JsonSerializationException CreateSerializationException(JsonReader reader, string message) - { - return CreateSerializationException(reader, message, null); - } - - private JsonSerializationException CreateSerializationException(JsonReader reader, string message, Exception ex) - { - return CreateSerializationException(reader as IJsonLineInfo, message, ex); - } - - private JsonSerializationException CreateSerializationException(IJsonLineInfo lineInfo, string message, Exception ex) - { - message = JsonReader.FormatExceptionMessage(lineInfo, message); - - return new JsonSerializationException(message, ex); + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } private JsonConverter GetConverter(JsonContract contract, JsonConverter memberConverter) @@ -352,7 +335,7 @@ namespace Newtonsoft.Json.Serialization { CheckedRead(reader); if (reader.TokenType != JsonToken.String && reader.TokenType != JsonToken.Null) - throw CreateSerializationException(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + throw JsonSerializationException.Create(reader, "JSON reference {0} property must have a string or null value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); string reference = (reader.Value != null) ? reader.Value.ToString() : null; @@ -361,7 +344,7 @@ namespace Newtonsoft.Json.Serialization if (reference != null) { if (reader.TokenType == JsonToken.PropertyName) - throw CreateSerializationException(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + throw JsonSerializationException.Create(reader, "Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); return Serializer.ReferenceResolver.ResolveReference(this, reference); } @@ -388,14 +371,14 @@ namespace Newtonsoft.Json.Serialization } catch (Exception ex) { - throw CreateSerializationException(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); + throw JsonSerializationException.Create(reader, "Error resolving type specified in JSON '{0}'.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName), ex); } if (specifiedType == null) - throw CreateSerializationException(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); + throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' was not resolved.".FormatWith(CultureInfo.InvariantCulture, qualifiedTypeName)); if (objectType != null && !objectType.IsAssignableFrom(specifiedType)) - throw CreateSerializationException(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); + throw JsonSerializationException.Create(reader, "Type specified in JSON '{0}' is not compatible with '{1}'.".FormatWith(CultureInfo.InvariantCulture, specifiedType.AssemblyQualifiedName, objectType.AssemblyQualifiedName)); objectType = specifiedType; contract = GetContractSafe(specifiedType); @@ -434,7 +417,7 @@ namespace Newtonsoft.Json.Serialization return CreateJObject(reader); if (contract == null) - throw CreateSerializationException(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); switch (contract.ContractType) { @@ -474,7 +457,7 @@ namespace Newtonsoft.Json.Serialization #endif } - throw CreateSerializationException(reader, @"Cannot deserialize JSON object (i.e. {{""name"":""value""}}) into type '{0}'. + throw JsonSerializationException.Create(reader, @"Cannot deserialize JSON object (i.e. {{""name"":""value""}}) into type '{0}'. The deserialized type should be a normal .NET type (i.e. not a primitive type like integer, not a collection type like an array or List) or a dictionary type (i.e. Dictionary). To force JSON objects to deserialize add the JsonObjectAttribute to the type.".FormatWith(CultureInfo.InvariantCulture, objectType)); } @@ -482,11 +465,11 @@ To force JSON objects to deserialize add the JsonObjectAttribute to the type.".F private JsonArrayContract EnsureArrayContract(JsonReader reader, Type objectType, JsonContract contract) { if (contract == null) - throw CreateSerializationException(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "Could not resolve type '{0}' to a JsonContract.".FormatWith(CultureInfo.InvariantCulture, objectType)); JsonArrayContract arrayContract = contract as JsonArrayContract; if (arrayContract == null) - throw CreateSerializationException(reader, @"Cannot deserialize JSON array (i.e. [1,2,3]) into type '{0}'. + throw JsonSerializationException.Create(reader, @"Cannot deserialize JSON array (i.e. [1,2,3]) into type '{0}'. The deserialized type must be an array or implement a collection interface like IEnumerable, ICollection or IList. To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".FormatWith(CultureInfo.InvariantCulture, objectType)); @@ -496,7 +479,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For private void CheckedRead(JsonReader reader) { if (!reader.Read()) - throw CreateSerializationException(reader, "Unexpected end when deserializing object."); + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } private object CreateList(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, object existingValue, string reference) @@ -560,7 +543,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For } catch (Exception ex) { - throw CreateSerializationException(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex); + throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, FormatValueForPrint(value), targetType), ex); } } @@ -672,7 +655,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) dictionary = contract.DefaultCreator(); else - throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); IWrappedDictionary dictionaryWrapper = contract.CreateWrapper(dictionary); @@ -707,7 +690,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For } catch (Exception ex) { - throw CreateSerializationException(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex); + throw JsonSerializationException.Create(reader, "Could not convert string '{0}' to dictionary key type '{1}'. Create a TypeConverter to convert from the string to the key type object.".FormatWith(CultureInfo.InvariantCulture, reader.Value, contract.DictionaryKeyType), ex); } if (contract.DictionaryValueContract == null) @@ -716,7 +699,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For JsonConverter dictionaryValueConverter = GetConverter(contract.DictionaryValueContract, null); if (!ReadForType(reader, contract.DictionaryValueContract, dictionaryValueConverter != null, false)) - throw CreateSerializationException(reader, "Unexpected end when deserializing object."); + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, contract.DictionaryValueContract, dictionaryValueConverter); } @@ -735,11 +718,11 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For return dictionary.UnderlyingDictionary; default: - throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (reader.Read()); - throw CreateSerializationException(reader, "Unexpected end when deserializing object."); + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } private object CreateAndPopulateList(JsonReader reader, string reference, JsonArrayContract contract) @@ -747,14 +730,14 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For return CollectionUtils.CreateAndPopulateList(contract.CreatedType, (l, isTemporaryListReference) => { if (reference != null && isTemporaryListReference) - throw CreateSerializationException(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Cannot preserve reference to array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); #if !PocketPC if (contract.OnSerializing != null && isTemporaryListReference) - throw CreateSerializationException(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Cannot call OnSerializing on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); #endif if (contract.OnError != null && isTemporaryListReference) - throw CreateSerializationException(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Cannot call OnError on an array or readonly list: {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); PopulateList(contract.CreateWrapper(l), reader, reference, contract); }); @@ -821,7 +804,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For } } - throw CreateSerializationException(reader, "Unexpected end when deserializing array."); + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing array."); } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) @@ -831,7 +814,7 @@ To force JSON arrays to deserialize add the JsonArrayAttribute to the type.".For if (!JsonTypeReflector.FullyTrusted) { - throw CreateSerializationException(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data. + throw JsonSerializationException.Create(reader, @"Type '{0}' implements ISerializable but cannot be deserialized using the ISerializable interface because the current application is not fully trusted and ISerializable can expose secure data. To fix this error either change the environment to be fully trusted, change the application to not deserialize the type, add to JsonObjectAttribute to the type or change the JsonSerializer setting ContractResolver to use a new DefaultContractResolver with IgnoreSerializableInterface set to true.".FormatWith(CultureInfo.InvariantCulture, objectType)); } @@ -845,7 +828,7 @@ To fix this error either change the environment to be fully trusted, change the case JsonToken.PropertyName: string memberName = reader.Value.ToString(); if (!reader.Read()) - throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); serializationInfo.AddValue(memberName, JToken.ReadFrom(reader)); break; @@ -855,12 +838,12 @@ To fix this error either change the environment to be fully trusted, change the exit = true; break; default: - throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); if (contract.ISerializableCreator == null) - throw CreateSerializationException(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType)); + throw JsonSerializationException.Create(reader, "ISerializable type '{0}' does not have a valid constructor. To correctly implement ISerializable a constructor that takes SerializationInfo and StreamingContext parameters should be present.".FormatWith(CultureInfo.InvariantCulture, objectType)); object createdObject = contract.ISerializableCreator(serializationInfo, Serializer.Context); @@ -881,13 +864,13 @@ To fix this error either change the environment to be fully trusted, change the IDynamicMetaObjectProvider newObject = null; if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract()) - throw CreateSerializationException(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (contract.DefaultCreator != null && (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator(); else - throw CreateSerializationException(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (id != null) Serializer.ReferenceResolver.AddReference(this, id, newObject); @@ -907,7 +890,7 @@ To fix this error either change the environment to be fully trusted, change the try { if (!reader.Read()) - throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); // first attempt to find a settable property, otherwise fall back to a dynamic set without type JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); @@ -945,7 +928,7 @@ To fix this error either change the environment to be fully trusted, change the exit = true; break; default: - throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); @@ -960,7 +943,7 @@ To fix this error either change the environment to be fully trusted, change the object newObject = null; if (contract.UnderlyingType.IsInterface() || contract.UnderlyingType.IsAbstract()) - throw CreateSerializationException(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); if (contract.OverrideConstructor != null) { @@ -984,7 +967,7 @@ To fix this error either change the environment to be fully trusted, change the } if (newObject == null) - throw CreateSerializationException(reader, "Unable to find a constructor to use for type {0}. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); + throw JsonSerializationException.Create(reader, "Unable to find a constructor to use for type {0}. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); PopulateObject(newObject, reader, contract, id); return newObject; @@ -1095,7 +1078,7 @@ To fix this error either change the environment to be fully trusted, change the JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter); if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false)) - throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (!property.Ignored) propertyValues[property] = CreateValueProperty(reader, property, propertyConverter, null, true, null); @@ -1105,10 +1088,10 @@ To fix this error either change the environment to be fully trusted, change the else { if (!reader.Read()) - throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) - throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); + throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, objectType.Name)); reader.Skip(); } @@ -1119,7 +1102,7 @@ To fix this error either change the environment to be fully trusted, change the exit = true; break; default: - throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (!exit && reader.Read()); @@ -1201,7 +1184,7 @@ To fix this error either change the environment to be fully trusted, change the if (property == null) { if (Serializer.MissingMemberHandling == MissingMemberHandling.Error) - throw CreateSerializationException(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); + throw JsonSerializationException.Create(reader, "Could not find member '{0}' on object of type '{1}'".FormatWith(CultureInfo.InvariantCulture, memberName, contract.UnderlyingType.Name)); reader.Skip(); continue; @@ -1213,7 +1196,7 @@ To fix this error either change the environment to be fully trusted, change the JsonConverter propertyConverter = GetConverter(property.PropertyContract, property.MemberConverter); if (!ReadForType(reader, property.PropertyContract, propertyConverter != null, false)) - throw CreateSerializationException(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); + throw JsonSerializationException.Create(reader, "Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); SetPropertyPresence(reader, property, propertiesPresence); @@ -1243,7 +1226,7 @@ To fix this error either change the environment to be fully trusted, change the { case PropertyPresence.None: if (property.Required == Required.AllowNull || property.Required == Required.Always) - throw CreateSerializationException(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + throw JsonSerializationException.Create(reader, "Required property '{0}' not found in JSON.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); if (property.PropertyContract == null) property.PropertyContract = GetContractSafe(property.PropertyType); @@ -1254,7 +1237,7 @@ To fix this error either change the environment to be fully trusted, change the break; case PropertyPresence.Null: if (property.Required == Required.Always) - throw CreateSerializationException(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); + throw JsonSerializationException.Create(reader, "Required property '{0}' expects a value but got null.".FormatWith(CultureInfo.InvariantCulture, property.PropertyName)); break; } } @@ -1275,11 +1258,11 @@ To fix this error either change the environment to be fully trusted, change the // ignore break; default: - throw CreateSerializationException(reader, "Unexpected token when deserializing object: " + reader.TokenType); + throw JsonSerializationException.Create(reader, "Unexpected token when deserializing object: " + reader.TokenType); } } while (reader.Read()); - throw CreateSerializationException(reader, "Unexpected end when deserializing object."); + throw JsonSerializationException.Create(reader, "Unexpected end when deserializing object."); } private void SetPropertyPresence(JsonReader reader, JsonProperty property, Dictionary requiredProperties) diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index 069f1d61..e4b79d74 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -136,7 +136,7 @@ namespace Newtonsoft.Json.Utilities } else { - throw new Exception("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType())); + throw new ArgumentException("Can not create ListWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, list.GetType()), "list"); } } @@ -167,7 +167,7 @@ namespace Newtonsoft.Json.Utilities #endif else { - throw new Exception("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType())); + throw new ArgumentException("Can not create DictionaryWrapper for type {0}.".FormatWith(CultureInfo.InvariantCulture, dictionary.GetType()), "dictionary"); } } @@ -237,7 +237,7 @@ namespace Newtonsoft.Json.Utilities } if (list == null) - throw new Exception("Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, listType)); + throw new InvalidOperationException("Cannot create and populate list type {0}.".FormatWith(CultureInfo.InvariantCulture, listType)); populateList(list, isReadOnlyOrFixedSize); diff --git a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs index a25c0477..24f2fa07 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionWrapper.cs @@ -170,7 +170,7 @@ namespace Newtonsoft.Json.Utilities int IList.IndexOf(object value) { if (_genericCollection != null) - throw new Exception("Wrapped ICollection does not support IndexOf."); + throw new InvalidOperationException("Wrapped ICollection does not support IndexOf."); if (IsCompatibleObject(value)) return _list.IndexOf((T)value); @@ -181,7 +181,7 @@ namespace Newtonsoft.Json.Utilities void IList.RemoveAt(int index) { if (_genericCollection != null) - throw new Exception("Wrapped ICollection does not support RemoveAt."); + throw new InvalidOperationException("Wrapped ICollection does not support RemoveAt."); _list.RemoveAt(index); } @@ -189,7 +189,7 @@ namespace Newtonsoft.Json.Utilities void IList.Insert(int index, object value) { if (_genericCollection != null) - throw new Exception("Wrapped ICollection does not support Insert."); + throw new InvalidOperationException("Wrapped ICollection does not support Insert."); VerifyValueType(value); _list.Insert(index, (T)value); @@ -218,14 +218,14 @@ namespace Newtonsoft.Json.Utilities get { if (_genericCollection != null) - throw new Exception("Wrapped ICollection does not support indexer."); + throw new InvalidOperationException("Wrapped ICollection does not support indexer."); return _list[index]; } set { if (_genericCollection != null) - throw new Exception("Wrapped ICollection does not support indexer."); + throw new InvalidOperationException("Wrapped ICollection does not support indexer."); VerifyValueType(value); _list[index] = (T)value; diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 33dc25ad..9bf50df2 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -376,7 +376,7 @@ namespace Newtonsoft.Json.Utilities return EnsureTypeAssignable(ToValue((INullable)initialValue), initialType, targetType); #endif - throw new Exception("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType)); + throw new InvalidOperationException("Can not convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, initialType, targetType)); } #endregion @@ -445,7 +445,7 @@ namespace Newtonsoft.Json.Utilities return null; } - throw new Exception("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); + throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType)); } #if !(SILVERLIGHT || NETFX_CORE || PORTABLE) @@ -464,7 +464,7 @@ namespace Newtonsoft.Json.Utilities else if (nullableValue is SqlDateTime) return ToValue((SqlDateTime)nullableValue); - throw new Exception("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType())); + throw new ArgumentException("Unsupported INullable type: {0}".FormatWith(CultureInfo.InvariantCulture, nullableValue.GetType())); } #endif diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index bb341b52..c7fd8884 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -130,7 +130,7 @@ namespace Newtonsoft.Json.Utilities ReflectionUtils.EmptyTypes, null); if (constructorInfo == null) - throw new Exception("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); + throw new ArgumentException("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type)); generator.Emit(OpCodes.Newobj, constructorInfo); } @@ -152,7 +152,7 @@ namespace Newtonsoft.Json.Utilities { MethodInfo getMethod = propertyInfo.GetGetMethod(true); if (getMethod == null) - throw new Exception("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); + throw new ArgumentException("Property '{0}' does not have a getter.".FormatWith(CultureInfo.InvariantCulture, propertyInfo.Name)); if (!getMethod.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); diff --git a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs index 7b04e451..d695172e 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -39,7 +39,7 @@ namespace Newtonsoft.Json.Utilities { Type binderType = Type.GetType(BinderTypeName, false); if (binderType == null) - throw new Exception("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName)); + throw new InvalidOperationException("Could not resolve type '{0}'. You may need to add a reference to Microsoft.CSharp.dll to work with dynamic types.".FormatWith(CultureInfo.InvariantCulture, BinderTypeName)); // None _getCSharpArgumentInfoArray = CreateSharpArgumentInfoArray(0); diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index 9dffba63..bf4e7c6f 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -42,7 +42,7 @@ namespace Newtonsoft.Json.Utilities Type enumType = typeof(T); if (!enumType.IsDefined(typeof(FlagsAttribute), false)) - throw new Exception("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType)); + throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType)); Type underlyingType = Enum.GetUnderlyingType(value.GetType()); @@ -96,7 +96,7 @@ namespace Newtonsoft.Json.Utilities } catch (OverflowException e) { - throw new Exception( + throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, "Value from enum with the underlying type of {0} cannot be added to dictionary with a value type of {1}. Value was too large: {2}", Enum.GetUnderlyingType(enumType), typeof(TUnderlyingType), Convert.ToUInt64(enumValues[i], CultureInfo.InvariantCulture)), e); }