-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplify JSON serialization of exceptions
+semver: patch
- Loading branch information
Showing
3 changed files
with
58 additions
and
5 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
namespace Mockaco.Common | ||
{ | ||
using Newtonsoft.Json; | ||
using Newtonsoft.Json.Linq; | ||
using System; | ||
|
||
internal class SimpleExceptionConverter : JsonConverter | ||
{ | ||
public override bool CanConvert(Type objectType) | ||
{ | ||
return typeof(Exception).IsAssignableFrom(objectType); | ||
} | ||
|
||
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | ||
{ | ||
throw new NotImplementedException("Deserializing exceptions is not supported."); | ||
} | ||
|
||
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | ||
{ | ||
var exception = value as Exception; | ||
if (exception == null) | ||
{ | ||
serializer.Serialize(writer, null); | ||
return; | ||
} | ||
|
||
var obj = new JObject | ||
{ | ||
["Type"] = exception.GetType().Name, | ||
["Message"] = exception.Message, | ||
|
||
}; | ||
|
||
if (exception.Data.Count > 0) | ||
{ | ||
obj["Data"] = JToken.FromObject(exception.Data, serializer); | ||
} | ||
|
||
if (exception.InnerException != null) | ||
{ | ||
obj["InnerException"] = JToken.FromObject(exception.InnerException, serializer); | ||
} | ||
|
||
obj.WriteTo(writer); | ||
} | ||
} | ||
|
||
} |
This file contains 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
This file contains 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