简体   繁体   中英

Proper way to rethrow a JsonConverter exception

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?)

Based on the Newtonsoft example here: https://www.newtonsoft.com/json/help/html/serializationerrorhandling.htm I 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM