Json.NET - Handling Errors

Json.NET supports two type of error handling, using the Error event and using OnErrorAttribute

The methods allows you to catch errors and allows it to handle it by you and continues the serialization process or it bubbles up the chain as an unhandled one

The Error event is defined in the JsonSerializer and this event fires whenever there is an error during serialization of deserialization process. You can use the JsonSerializerSettings instance to set the Error event.

In this example, I have created a delegate for the error event, which will add the error to a collection. Here, I have intentionally entered a string for the DateTime field so that an exception will occur during the conversion process. When the exception occurs, it's catched by our delegate, adds it to the collection and set the Handled property to true so that it's not bubbled up.

You can see that eventhough the exception has occured, it doesn't stop the conversion process with the rest of the items.

OnError Attribute

You can use this attribute on the class like any other attribute so far in this series. To use this one, just decorate the method you want to handle the error with the attribute [OnError] as shown below

[OnError]
internal void OnError(StreamingContext context, ErrorContext errorContext)
    {
        errorContext.Handled = true;
    }


No Comments

Add a Comment