简体   繁体   English

重新抛出 JsonConverter 异常的正确方法

[英]Proper way to rethrow a JsonConverter exception

I have the following setup for deserializing some json:我有以下设置用于反序列化一些 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.在一种情况下, json有一堆空值(如"title" : null,等),这会在我的一个转换器中导致 NullReferenceException。 But throwing MyParseException in the error handler causes但是在错误处理程序中抛出MyParseException会导致

System.InvalidOperationException: Current error context error is different to requested error. System.InvalidOperationException:当前错误上下文错误与请求的错误不同。

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:基于此处的 Newtonsoft 示例: https : //www.newtonsoft.com/json/help/html/serializationerrorhandling.htm我最终执行了以下操作:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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