When error handlers go wrong

It is good to create an error handler for your code and ASP.NET is no exception.  But there are some things to keep in mind when you are writing the code that will handle the exception.  Most notably, don't have your function or any function you call throw an unhandled exception.  Here is the common scenario:

  • Exception occurs in a web page
  • Error handler in Global.asax handles the exception
  • Error handler calls a function to log the error the the Event Log
  • Event Log function fails to add the entry due to permissions and throws another exception
  • Error handler catches this exception and tries to log it also.

This will cause ASP.NET to go into an endless loop until we run out of stack space and crash.

When this happens, you won't get a very descriptive message in the Event Log, you will see something like (Note that other problems can lead to this error message as this is just telling you the process crashed) :

 Event Type: Warning
Event Source: W3SVC
Event Category: None
Event ID: 1011
Date: 24-09-2007
Time: 11:46:49
User: N/A
Computer: TESTCOMP
Description:
A process serving application pool 'Testing' suffered a fatal 
communication error with the World Wide Web Publishing Service. The process id was 
'5796'. The data field contains the error number. 

For more information, see Help and Support Center at 
.
Data:
0000: 6d 00 07 80

If you get a dump of the process when it crashes, using DebugDiag for example.  You will see a managed stack that repeats, looking something like:

 Tester!modErrorHandling::WriteToLog+0x411 
Tester!modErrorHandling::WriteToEventLog+0x1b0 
Tester!modErrorHandling::ReportError+0x1a
Tester!modErrorHandling::WriteToLog+0x411 
Tester!modErrorHandling::WriteToEventLog+0x1b0 
Tester!modErrorHandling::ReportError+0x1a
Tester!modErrorHandling::WriteToLog+0x411 
Tester!modErrorHandling::WriteToEventLog+0x1b0 
Tester!modErrorHandling::ReportError+0x1a
...

So to correct this, either make sure you put all code inside a try/catch for Exception Handlers or don't make calls that can throw an exception.