Categories
.NET Core

Understanding the Newtonsoft JSON Token

One of the concepts worth understanding when writing a custom converter for the popular Newtonsoft JSON framework is that of the JsonToken, and the role it plays in helping you understand the JSON being read.

The JsonToken documentation for Newtonsoft is relatively sparse – in part because once you understand it, it’s a relatively simple concept.

Effectively, when you’re attempting to deserialise a string representation of a JSON object, such as in the ReadJson method of a custom JsonConverter, the JsonToken represents each element or component (token if you prefer) of the object as it’s deserialised.

So for example, if you have the following JSON and implement the ReadJson method:

{	"message": "Hello world"}

When you first get the reader.TokenType value you’ll get JsonToken.StartObject back – this represents that the { implies that you’re first reading an object element.

If you were to then call reader.ReadAsync(), and then subsequently request the reader.TokenType again now you’ll get JsonToken.PropertyName in response. This is because the next element within the JSON string is the property name (in other words, the “message” key).

Lastly, if you were to call reader.ReadAsync() for a third time, you’d get back JsonToken.String as the value of the property is a string (“Hello world”). NewtonSoft will try and parse the value into a representation of a type – so for example, if that was a number, you’d get back Integer of Float, and if it was a Boolean you’d get back Boolean.

Categories
.NET Core

Throw or throw ex in C#?

One common question that comes up when working with exceptions in C#, is whether or not you should re-throw an existing exception by specifying the exception, or just using the throw keyword where an error occurs.

In most cases, it’s best to rethrow the existing exception, such as below:

try {	var networkResponse = await someNetworkService.GetAllPosts();}catch (Exception ex){	Log.Warning("An exception occurred", ex);	//Now lets rethrow this same exception	throw;}

By doing so, you ensure that the original stack trace for the exception is maintained. If you were to instead do something like this:

try {	var networkResponse = await someNetworkService.GetAllPosts();}catch (Exception ex){	Log.Warning("An exception occurred", ex);	//Now lets throw ex again	throw ex;}

You’ll now see that the exception stack trace only goes as far back as this line of code – not to the raw source of the exception.

In short, that’s why its normally better to just throw again, instead of specifying the exception when re-throwing.