Monday, December 07, 2009

ASP.NET AJAX calling webservice has exception handling bug

[This is a re-post from my previous blog]

When using Microsoft ASP.NET AJAX, you can call any webservice you have enabled with the [ScriptService] attribute. This webservice could throw an exception, which ends up on the webpage as a javascript alert. This all works quite nicely, UNTIL you actually deploy such a solution!

Let's say you have a webservice that takes an item and returns some status about that item. When coding your webservice, if you cannot find the item (client passed in an invalid number), you throw an InvalidItemException with a message of 'Item Not Found'. You test this and everything works in development, but when you deploy you get a generic message of 'There was an error processing the request' when the item is not found.

Turns out, this is because you have (Of course you do, this is a real live site!). When this is set to off, the exception message from the webservice is not shown also. This is of course unacceptable, because you intended that message to show. It turns out, this is by design. The asp.net team is trying to prevent internal details from showing up to users. This is all great and fine, but what in the world are you supposed to do to handle this situation? You could return a custom type, that had an error flag, description, and regular result data - what...are you kidding me...that would be crazy. Or you could do as some others and just not use it!

Here is an easy solution to this problem. Place all your webservices where you WANT the exception message to be shown in their own separate directory. Then in that directory, put a web.config file that contains and presto, your thrown exceptions now show the correct message! (Be careful and make sure other exceptions thrown by your service would not expose internal details. You could wrap the service method in a try/catch block allowing your custom exceptions to escape and suppressing the 'internal data' on the others)

Here are a couple of related blog entries on this same problem.

http://blog.hackedbrain.com/archive/2007/08/03/6121.aspx

http://jlchereau.blogspot.com/2007/03/ajax-extensions-services-always-report.html

Good luck!

No comments: