Home > Blockchain >  Proper way to rethrow a JsonConverter exception
Proper way to rethrow a JsonConverter exception

Time:11-18

I have the following setup for deserializing some json:

parsedResponse = JsonConvert.DeserializeObject<T>(
  json,
  new JsonSerializerSettings
  {
    Error = (object sender, ErrorEventArgs args) =>
    {
      throw new MyParseException($"Parse error: {args.ErrorContext.Error.Message}");
    },
    Converters =
    {
      new MyItemConverter(),
      new BoolConverter(),
      new UnixDateTimeConverter(),
      new NullableIntConverter(),
      new UriConverter()
    }
  }
);

In one case, json has a bunch of null values (like "title" : null, etc) which causes a NullReferenceException in one of my converters. But throwing MyParseException in the error handler causes

System.InvalidOperationException: Current error context error is different to requested error.

I think I could do this instead:

try
{
    parsedResponse = JsonConvert.DeserializeObject<T>(
      json,
      new JsonSerializerSettings
      {
        Converters =
        {
          new MyItemConverter(),
          new BoolConverter(),
          new UnixDateTimeConverter(),
          new NullableIntConverter(),
          new UriConverter()
        }
      }
    );
}
catch (Exception ex)
{
    throw new MyParseException($"Parse error: {ex.Message}");
}

But is there a better way? (Maybe something more similar to my original solution that doesn't cause the error context issue?)

CodePudding user response:

Based on the Newtonsoft example here. I've ended up doing the following:

List<MyParseException> errors = new List<MyParseException>();

T parsedResponse = JsonConvert.DeserializeObject<T>(
  json,
  new JsonSerializerSettings
  {
    Error = (object sender, ErrorEventArgs args) =>
    {
      errors.Add(new MyParseException(String.Format("Parse error: {0}", args.ErrorContext.Error.Message), args.ErrorContext.Error));
      args.ErrorContext.Handled = true;
    },
    Converters =
    {
      new MyItemConverter(),
      new BoolConverter(),
      new UnixDateTimeConverter(),
      new NullableIntConverter(),
      new UriConverter()
    }
  }
);

if (errors.Count == 1)
{
  MyParseException firstException = errors[0];
  firstException.Data["json"] = json;
  throw firstException;
}
else if (errors.Count > 1)
{
  AggregateException ex = new AggregateException("Unable to parse json. See innner exceptions and exception.Data[\"json\"] for details", errors);
  ex.Data["json"] = json;
  throw ex;
}
  • Related