Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

Deserialize exception from JSON string

My WebApi throws an internal server exception, and in the client I'm trying to deserialize back the result in an exception.

The controller's action does:

try
{
    //Do something...
}
catch (Exception ex)
{
    return InternalServerError(ex);
}

And in the client I'm doing:

var content = response.Content.ReadAsStringAsync().Result;
var exception = JsonConvert.DeserializeObject<Exception>(content);

But an exception is thrown:

Member 'ClassName' was not found.

Checking the context with Json2csharp, I get the following objects:

public class InnerException
{
    public string Message { get; set; }
    public string ExceptionMessage { get; set; }
    public string ExceptionType { get; set; }
    public string StackTrace { get; set; }
}

public class RootObject
{
    public string Message { get; set; }
    public string ExceptionMessage { get; set; }
    public string ExceptionType { get; set; }
    public string StackTrace { get; set; }
    public InnerException InnerException { get; set; }
}

So where is the ClassName coming from, and what is the best way to deserialize an exception?

EDIT

To serialize the exception I created a new class derived from Exception, and added the following code:

    protected RequestException(SerializationInfo info, StreamingContext context)
    {
    }

    [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);
    }

However, the original exception details, especially the inner exception, are lost.

Upvotes: 2

Views: 6886

Answers (1)

or hor
or hor

Reputation: 723

do not expose exception itself, create your own response object with inner properties, in case of exception fill your own object and pass it to response. on client side use

var content = response.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<MyResponseObject>(content);

Upvotes: 2

Related Questions