4

I'm using the common practice of catching errors in global.asax in my ASP.net application. In global.asax, I have a function Application_Error that logs the errors to the database.

This works very well to log errors that occur when the user requests a page.

However, this does nothing to help when an asynchronous method (a method decorated with the [WebMethod] attribute) called from the client-side throws an exception. The exception simply bubbles up and may be returned to the client-side code, but I would like to have the error handling code run on the server automatically similar to how page errors are logged in global.asax.

How do I accomplish this? One way would be to wrap every single asynchronous method with try-catch, but this doesn't seem like a good solution to me.

Vivian River
  • 31,198
  • 62
  • 198
  • 313

2 Answers2

0

One option is to create an ASP.NET output filter that intercepts and logs WebMethod exceptions sent by ASP.NET to the client. Here's the basic idea:

  1. Create a subclass of Stream that captures the content of the response.
  2. When the stream is closed, check whether the response has a 500 status code as well as a "jsonerror: true" header. If so, the response contains a WebMethod exception; log the exception.
  3. In Global.Application_PostMapRequestHandler, install an instance of this class as the output filter for JSON requests.

For complete source code, see this StackOverflow answer.

Michael Liu
  • 52,147
  • 13
  • 117
  • 150
-2

How to create a global exception handler for a Web Service

Akhil
  • 7,570
  • 1
  • 24
  • 23
  • That approach does not appear to be valid for calling WebMethods via AJAX GET/POST, only for SOAP webservice calls. – Carson63000 Jun 05 '14 at 07:39