How to serialise Exception to Json
14,097
Since this has not really been answered yet: Just create a Dictionary containing the error properties you want, serialize it using JSON.NET and put it into a 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;
}
I hope this can help some people out.
Related videos on Youtube
Author by
user1919249
Updated on June 15, 2022Comments
-
user1919249 about 2 years
C# Exceptions are ISerialisable so they can't also be DataContracts so I can't use JsonDataContractSerializer.
What are alternatives to serialising Exceptions to JSON?
-
Mainul over 8 yearspossible duplicate stackoverflow.com/questions/486460/…
-
Khan Abdulrehman over 8 years
-