Created
September 11, 2024 08:20
-
-
Save mesuttalebi/f1603cc5aea6099c906cc0707a8780ec to your computer and use it in GitHub Desktop.
A JsonConverter for serializing Exceptions using System.Text.Json.JsonSerializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ExceptionConverter<TExceptionType> : JsonConverter<TExceptionType> where TExceptionType : Exception | |
{ | |
public override bool CanConvert(Type typeToConvert) => typeof(Exception).IsAssignableFrom(typeToConvert); | |
public override TExceptionType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
=> throw new NotSupportedException("Deserializing exceptions is not allowed"); | |
public override void Write(Utf8JsonWriter writer, TExceptionType value, JsonSerializerOptions options) | |
{ | |
var serializableProperties = value.GetType() | |
.GetProperties() | |
.Select(uu => new { uu.Name, Value = uu.GetValue(value) }) | |
.Where(uu => uu.Name != nameof(Exception.TargetSite)); | |
if (options?.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingNull) | |
{ | |
serializableProperties = serializableProperties.Where(uu => uu.Value != null); | |
} | |
var propList = serializableProperties.ToList(); | |
if (propList.Count == 0) | |
{ | |
// Nothing to write | |
return; | |
} | |
writer.WriteStartObject(); | |
foreach (var prop in propList) | |
{ | |
writer.WritePropertyName(prop.Name); | |
JsonSerializer.Serialize(writer, prop.Value, options); | |
} | |
writer.WriteEndObject(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment