Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialise Exception to Json

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?

like image 684
user1919249 Avatar asked Feb 12 '16 08:02

user1919249


1 Answers

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.

like image 98
Johan Wintgens Avatar answered Sep 17 '22 10:09

Johan Wintgens