How to Serialize an Exception Object in C#

How to serialize an Exception object in C#?

What I've done before is create a custom Error class. This encapsulates all the relevant information about an Exception and is XML serializable.

[Serializable]
public class Error
{
public DateTime TimeStamp { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }

public Error()
{
this.TimeStamp = DateTime.Now;
}

public Error(string Message) : this()
{
this.Message = Message;
}

public Error(System.Exception ex) : this(ex.Message)
{
this.StackTrace = ex.StackTrace;
}

public override string ToString()
{
return this.Message + this.StackTrace;
}
}

Serializing custom exception object

I wish but I can't fall outside with 3rd party libraries, only native implementations because of some requirements.

You can include the System.Web.Extensions library and use JavaScriptSerializer

var ser = new JavaScriptSerializer();
string json = ser.Serialize(exception);

But as I said in comments, I would prefer Json.Net

How can I serialize my exceptions inside an ASP.NET application?

I usually use a helper function that deals with exception handling in my Web API projects. I pass the exception that's thrown as an argument to it, then return a HttpResponseException and throw that.

The thrown exception will automatically be serialized to the return type of your Http verb function. In my example I return a Task as it'll serialize any .Net type to a generic object.

If you look at my example below you'll see I have a Method called Get that has its return type set to Task. The object type will be serialized to JSON if the front-end app performs a HTTP GET (in your case a POST) with the Accept header set to 'application/json', when the method returns it'll serialize the return type of Task to json. This also works for the Accept type of text/xml.

I'd recommend filtering specific data in your helper method. you probably don't want people consuming your API to get full stack traces and the like after all, but obviously this is down to your requirements.

public async Task<Object> Get()
{
object result = null;
try
{
result = await methodThatThrowsException();
}
catch (Exception ex)
{
throw CreateHttpResponseException(ex);
}
return result;
}

Helper Method

private HttpResponseException CreateHttpResponseException(Exception ex)
{
HttpResponseMessage message;
if (ex.GetType() == typeof(FaultException<LoginFault>))
{
message = new HttpResponseMessage(HttpStatusCode.Forbidden);
}
else
{
message = new HttpResponseMessage(HttpStatusCode.InternalServerError);
}

message.Content = new StringContent(ex.Message);
return new HttpResponseException(message);
}

In the helper Method, use a StringBuilder to build up what you want to display in your front end. Concatenate and format your error message as you require and then assign the string value to your MessageResponseMessage.Content field.

You'll need to iterate over the Exception InnerException and check to see if it's null, concatenating the exception message etc... as you need.

You could iterate over inner Exceptions using something like

StringBuilder exceptionMessage = new StringBuilder();
Exception inner = ex.InnerException;
while (inner != null)
{
exceptionMessage.Append(inner.Message)
.Append(Environment.NewLine);
inner = inner.InnerException;
}

In C#, how can I serialize System.Exception? (.Net CF 2.0)

I think you basically have two options:

  1. Do your own manual serialization (probably do NOT want to do that). XML serialization will surely not work due to the exact message you get in the inner exception.
  2. Create your own custom (serializable) exception class, inject data from the thrown Exception into your custom one and serialize that.

How to serialize an exception in Azure Service Bus?

You won't be able to serialize your exception with DataContractSerializer. Even if you marked your class with DataContract successfully, the inner exception can be of any type, thus not compatible.

So you have two options:

  1. Serialize your exception with another serializer (and then pass the Stream to BrokeredMessage constructor). See this question for some options.

  2. I would argue that sending the exception itself over the wire isn't very clean. I'd rather create a custom message which contains all the information that is important to consumers, and then send this message to Service Bus.



Related Topics



Leave a reply



Submit