I’m using the [System.Web.Script.Services.ScriptService] tag to use web services callable from client side javascript. What I need is a way of globally logging any unhandled exceptions in those methods. On the client side, I get the error callback and can proceed from there, but I need a server-side catch to log the exception.
The guy at this url: http://ayende.com/Blog/archive/2008/01/06/ASP.Net-Ajax-Error-Handling-and-WTF.aspx
suggests that this can’t be done.
Is that accurate? Do I seriously have to go to every single webmethod in the entire system and try/catch the method as a whole.
You can use an HTTP module to capture the exception message, stack trace and exception type that is thrown by the web service method.
First some background…
If a web service method throws an exception the HTTP response has a status code of 500.
If custom errors are off then the web service will return the exception message and stack trace to the client as JSON. For example:
{'Message':'Exception message','StackTrace':' at WebApplication.HelloService.HelloWorld() in C:\Projects\Stackoverflow Examples\WebApplication\WebApplication\HelloService.asmx.cs:line 22','ExceptionType':'System.ApplicationException'}When custom errors are on then the web service returns a default message to the client and removes the stack trace and exception type:
{'Message':'There was an error processing the request.','StackTrace':'','ExceptionType':''}So what we need to do is set custom errors off for the web service and plug in an HTTP module that:
The code below is an example of an HTTP module that does this:
This module uses the following filter to override the content sent to the client and to store the original bytes (which contain the exception message, stack trace and exception type):
This method requires custom errors to be switched off for the web services. You would probably want to keep custom errors on for the rest of the application so the web services should be placed in a sub directory. Custom errors can be switched off in that directory only using a web.config that overrides the parent setting.