added custom error display

2007-08-23 @ 23:09#

i added a custom error display for the exyus framework today. this is another way for me to hide my web tech. it's not that i don't *like* ASP.NET, but i just want to keep the details under wraps [g].

btw, there's a bit of a 'trick' to overriding the default ASP.NET error display. while the ASP.NET system allows you to register to customErrors redirect, that's a bad idea. what that does is reroute error requests to another page. that results in sending the client some meaningful text along with an HTTP status code of 200. this is nice for humans, but bad for robots and other machine-level clients.

instead, i implemented an HttpModule that responds to the Application_Error event. then i can do whatever i like such as write logs, send emails, and send content to the client. so far, i'm just sending simple text to the client along with the proper status code. in the future, i might write certain messages to a log file, etc.

below is my entire custom error handler module. note that i explicitly end and close the connection to the client. this is the only way to keep the ASP.NET framework from spitting out it's own error display. took me a few tries to figure that out!


public class ErrorModule : IHttpModule
{
    public String ModuleName
    {
        get { return "ErrorModule"; }
    }

    public void Init(HttpApplication application)
    {
        application.Error += (new EventHandler(this.Application_Error));
    }

    private void Application_Error(Object source, EventArgs e)
    {
        HttpApplication app = (HttpApplication)source;
        HttpResponse response = app.Response;

        try
        {
            HttpException hex = (HttpException)app.Context.Error;
            response.StatusCode = hex.GetHttpCode();
            response.Write(
                string.Format(
                    Constants.fmt_error_module, 
                    hex.GetHttpCode(), 
                    hex.Message)
                );
        }
        catch (Exception ex)
        {
            response.StatusCode = 500;
            response.Write(
                string.Format(
                    Constants.fmt_error_module, 
                    500, 
                    ex.Message)
                );
        }

        response.Flush();
        response.End();
        response.Close();
    }

    public void Dispose() { }
}

code