简体   繁体   中英

How to serialize a custom exception to json in c#

I have ac# web service that I call using jquery ajax. It works fine except when a custom exception is throw inside the web method. For some reason, the XmlHttpResponse objects responseText only has the base Exception class's properties. So I end up with a json object with the following properties: "ExceptionType", "Message", and "StackTrace"

My custom exception has a property called "FieldErrors" that doesn't not show up in the return. Here's the code for that class:

[Serializable]
[XmlRootAttribute(Namespace = "http://www.mydomain.com/", IsNullable = false)]
public class ValidationException : Exception
{
    public List<string> FieldErrors { get; set; }
    public ValidationException(string message = null, Exception innerException = null) : base(message: message, innerException: innerException) 
    {
        this.FieldErrors = new List<string>();
    }
}

My goal is to get the "FieldErrors" property to show up in the json response.

Don't do this. You should never expose exceptions from your asp.net site.

Even if it will end up hidden to the user, you are still sending it with all its detail to the client.

In this case you actually want to control what will be sent, so explicitly sending the list of field errors without sending the json version of the whole exception instance is what you should be doing anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM