Handling Errors in ASP.NET

The other day, I was working through some code, adding error handling. We use the Enterprise Instrumentation Framework to do this (oddly only available via MSDN Subscriber download at the Universal level). When I got into the ASP.NET web pages I’d written, I had a bit of a problem. I didn’t really want to add try/catch blocks around every single method in the page’s base class – that would be a little redundant, and would mean that I’d have to change code in a bunch of places if I decided to change the style of errors I was reporting.

This is where it pays to be friends with Fritz Onion. :) I pinged him, and he suggested a clever little hack (in the good sense of that word) to put all my error handling code in one place.

The trick is to re-implement IHttpHandler on the page class itself. Since IHttpHandler is the one entry point for all requests into the page – whether that’s a callback handler for an event from the client or the initial Page_Load call – I could simply delegate back to the Page class’s ProcessRequest, but catch any errors that came out of it. One place to put all my high-level error handling. And I could even rethrow the exception if I wanted to still use ASP.NET’s built-in error handling.

It goes something like this:

using System; using System.Web ; using System.Web.UI ; using System.Web.UI.WebControls ; public class Default : Page, IHttpHandler { public void ProcessRequest ( HttpContext ctx ) { try { // Let the Page class itself handle the processing, as usual base.ProcessRequest ( ctx ); } catch (Exception e) { // Log it here – event log, EIF, whatever // Use our own error page or simply re-throw ctx.Response.Redirect ("myerror.aspx"); } } public void Page_Load (object o, EventArgs e) { throw new ApplicationException ("Whoops"); } public void Button_OnClick (object o, EventArgs e) { throw new ApplicationException (" Aiieeeee !!!"); } }

Comments

Why not just wire up to the Error event? -- KeithBrown [2004-07-20]

I dunno. Ask Fritz. :) In fact, there are a number of appraoches one could use. Brad Wilson has an article addressing alternate approaches here. -- CraigAndera [2004-07-20]

Cool! [2004-09-05]