簡體   English   中英

如何將異常序列化為 Json

[英]How to serialise Exception to Json

C# 異常是可序列化的,所以它們也不能是 DataContracts,所以我不能使用 JsonDataContractSerializer。

將異常序列化為 JSON 的替代方法是什么?

由於這還沒有真正得到回答:只需創建一個包含所需錯誤屬性的字典,使用 JSON.NET 對其進行序列化並將其放入HttpResponseMessage

catch (Exception e)
{
    var error = new Dictionary<string, string>
    {
        {"Type", e.GetType().ToString()},
        {"Message", e.Message},
        {"StackTrace", e.StackTrace}
    };

    foreach (DictionaryEntry data in e.Data)
        error.Add(data.Key.ToString(), data.Value.ToString());

    string json = JsonConvert.SerializeObject(error, Formatting.Indented);

    HttpResponseMessage response = new HttpResponseMessage();
    response.Content = new StringContent(json);

    return response;
}

我希望這可以幫助一些人。

這是我在我的項目中使用的解決方案,它有一些期望的優勢(恕我直言):

  • 非常干凈的 JSON 格式
  • 內部異常的遞歸轉儲
using System.Text.Json.Serialization;

namespace MyAwesomeroject.Shared.Utils;

public static class ExceptionExtensions
{
    public class ExceptionInfo
    {
        public ExceptionInfo() { }

        internal ExceptionInfo(Exception exception, bool includeInnerException = true, bool includeStackTrace = false)
        {
            if (exception is null)
            {
                throw new ArgumentNullException(nameof(exception));
            }

            Type = exception.GetType().FullName;
            Message = exception.Message;
            Source = exception.Source;
            StackTrace = includeStackTrace ? exception.StackTrace : null;
            if (includeInnerException && exception.InnerException is not null)
            {
                InnerException = new ExceptionInfo(exception.InnerException, includeInnerException, includeStackTrace);
            }
        }

        public string Type { get; set; }
        public string Message { get; set; }
        public string Source { get; set; }
        public string StackTrace { get; set; }
        public ExceptionInfo InnerException { get; set; }
    }

    private static readonly JsonSerializerOptions _defaultJsonSerializerOptions = new()
    {
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        WriteIndented = true,
    };

    /// <summary>
    /// Serialize the <see cref="Exception"/> to a JSON string.
    /// </summary>
    /// <param name="ex">The exception</param>
    /// <param name="includeInnerException">Control if to include inner exception</param>
    /// <param name="includeStackTrace">Control if to include stack trace</param>
    /// <param name="options">JSON options. By default nulls are not serialized and the string is indented</param>
    /// <returns></returns>
    public static string ToJson(
        this Exception ex,
        bool includeInnerException = true,
        bool includeStackTrace = false,
        JsonSerializerOptions options = null)
    {
        ArgumentNullException.ThrowIfNull(ex);
        var info = new ExceptionInfo(ex, includeInnerException, includeStackTrace);
        
        return JsonSerializer.Serialize(info, options ?? _defaultJsonSerializerOptions);
    }
}

這會產生如下輸出:

{
  "Type": "System.InvalidOperationException",
  "Message": "MyMessage",
  "Source": "MySource",
  "InnerException": {
    "Type": "System.ArgumentException",
    "Message": "MyInnerMessage",
    "Source": "MyAwesomeProject.Utils.Tests",
    "StackTrace": "   at MyAwesomeProject.Utils.Tests.ExceptionExtensionsTests.ShouldInclude_StackTrace_if_required() in /Users/jc/git/MyAwesomeProject/tests/Shared/Utils/ExceptionExtensionsTests.cs:line 41"
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM