0

I can“t get the properties values created on BaseException when call to Get api method. Any idea why?

public class BaseException : Exception
{
    public  string ExType { get; set; }

    public JObject Properties { get; set; }

    public Guid ErrorCodeId { get; set; }

    public BaseException(string message): base(message) { }
}

public class BadRequestException : BaseException
{
    public BadRequestException(string message) : base(message) { }
}

// GET: api/<controller>
public virtual IHttpActionResult Get()
{
    IHttpActionResult result = null;
    try
    {
        throw new Exception("Error description here");
        result = Ok();
    }
    catch (Exception ex)
    {
        result = ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, new BadRequestException(ex.Message)
        {
            ExType = "Any exception type"//Can't get this value in the output JSON
        }));
    }
    return result;
}

ExType value is not showing. The result that I got is the following:

{
  "ClassName": "BadRequestException",
  "Message": "Error description here",
  "Data": null,
  "InnerException": null,
  "HelpURL": null,
  "StackTraceString": null,
  "RemoteStackTraceString": null,
  "RemoteStackIndex": 0,
  "ExceptionMethod": null,
  "HResult": -2146233088,
  "Source": null,
  "WatsonBuckets": null
}

There is any way to get the serealized value of my own properties?

gsubiran
  • 2,012
  • 1
  • 22
  • 33

1 Answers1

0

Well regarding to this answer What is the correct way to make a custom .NET Exception serializable? .

Is needed to explicitly add the new properties when serializing an object of custom inherited class from Exception. To do that we should override the GetObjectData method and put into info all properties and values that you want to serialize.

public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
    base.GetObjectData(info, context);
}

Great, so to automate that we could use reflection as follows

public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
    //Getting first from base
    base.GetObjectData(info, context);

    if (info != null)
    {
        foreach (PropertyInfo property in this.GetType().GetProperties())
        {
            //Adding only properties that not already declared on Exception class
            if (property.DeclaringType.Name != typeof(Exception).Name)
            {
                info.AddValue(property.Name, property.GetValue(this));
            }
        }
    }
}

Then when serializing all custom properties apear in the output.

gsubiran
  • 2,012
  • 1
  • 22
  • 33