Search code examples
jqueryasp.netjsonexceptionwebmethod

Adding Exception Information on ASP.NET WebMethods called by JQuery Ajax


I am using ASP.NET WebMethods that are called by jQuery / ajax in JSON Format.

I have to improve the exception handling by providing more information for the user.

I catch the original exception and I throw an "UserFriendlyException" where only a "Headline" and "Description" is set.

I only get a very basic JSON String {"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}

I was looking for some solutions and found pages like: http://encosia.com/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/ or https://stackoverflow.com/a/891442/1099519

where you could access the message, which is fine, but still I wanted to access multiple properties. Most of the articles I've seen usually recommend to use the statusCode for an "ID" more than less.

I thought of a different approch: Propably there is a way, to override the rendering of exceptions in someway (like it is possible in WCF to modify the complete message), so in this case I could catch somehow my UserException and render a JSON string by my very own?

Any ideas?

Thanks for help, Dominik


Solution

  • I actually solved it in a very different way. I couldn't add any more information to the exception, so I needed to find another solution:

    I created a JsonException which I simply can pass an "JsonContainer" Object and when calling ToString(), I escape the properties in the JsonContainer to a Json String.

    So in the end, the message of the Exception was a Json-String containing all the information I wanted and i could parse it in JQuery like this:

    if (data.responseJSON && data.responseJSON.ExceptionType == "InhouseWKOIT.Framework.BusinessEntities.Web.JsonContainerException") {
      var messageObject = JSON.parse(data.responseJSON.Message);
      var someInformation = messageObject.MyProperty1;
      var someMoreInformation = messageObject.MoreInformation;
    }
    

    This works pretty fine, nice & smoothly :-)

    The browser only needs to support the JSON.parse method (either natively or using a plugin)