Posts Tagged ‘Exception Handling’

An Exception Handling system

Saturday, February 16th, 2008

I was having a problem where thrown .Net errors were showing up on a web site, but didn’t always want the entirely hide the errors, since sometimes the system purposely threw errors with messages that were intended for the user. (“You selected an invalid object for this operation”-type messages) However, unexpected errors, such as SQL errors needed to be entirely hidden. Either way, I wanted the thrown message to be automatically logged via log4net, and a “friendly” error page displayed. Lastly, I wanted this system to be easily reusable on future websites.

To handle this situation, I set up my own Exception class that extended the system exception class, called ApplicationException. All errors that were purposely thrown with a message that SHOULD be seen my the end user throw an ApplicationException instead of a plain Exception. Errors I didn’t expect would come in as plain old Exceptions.

I also set up an HttpModule that caught the application_errors, and would check the type of the actual exception, logged via log4net whether it was a regular Exception or an ApplicationException., and then did a Server.Transfer to an error page. (pulled from the appSettings) It needs to do the Server.Transfer (grabbed from the context) instead of the web.config error setting, by the way, because otherwise the error page won’t be able to access the Exception object! Anyway, then, those two files get pulled into error handling dll.. the HttpModule gets pointed to in the project’s .config, and the logging portion is done. Potentially, the system might also send out an email at this point, letting the developers know.
All that’s then needed is the actual error page(named in the .config file and referred to from the HttpModule) That page also switches on the Exception type… if it’s an ApplicationException, display the generated message inside the exception. Otherwise, it just displays a generic “Sorry, there’s been an error” message. This logic could/should probably also go into the ErrorHandling library, but the actual page can be site specific so each site can have a pretty site-matching error page, with a message telling the user what to do and who to contact, as appropriate.