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.

Share:
14,097

Related videos on Youtube

user1919249
Author by

user1919249

Updated on June 15, 2022

Comments