views:

91

answers:

1

I have a c# 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.

+1  A: 

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.

eglasius
Thanks. Good suggestion. I would still like to know how to do it though. This brings up another question, how do I return just the list of field errors and be able to handle that in the ajax "error" callback? Do I have to manually set the response code to 500 before returning the errors?
fehays
yes, you set the response code to 500 to indicate error to the caller. Something somewhat unrelated / unlikely the case but I want to add: if you happen to be decrypting anything in the request, make sure the response is exactly the same when the api fails to decrypt (because of the padding) vs. it fails because the decrypted value is garbage. That's what the padding oracle vulnerability out there is about. Also if doing that, its best to add a signature.
eglasius