views:

42

answers:

3

In asp.net, I can define a custom error page like this:

    <configuration>
    <system.web>
        <customErrors mode="On">
            <error statusCode="404" redirect="/servererrors/404.aspx" />
        </customErrors>
    </system.web>
</configuration>

Now my question: If I replace, say 404.aspx with AnyHTTP.aspx, and want to get the number of the http error to generalize the page, how do I get that error numer?

A: 

Well you might take a look at http://www.raboof.com/projects/Elmah/ before you venture to deep into doing your own thing...

Yves M.
+1  A: 

Try this setting in CustomErrors (ASP.NET 3.5 SP1):

<customErrors mode="RemoteOnly" defaultRedirect="/servererrors/AnyHTTP.aspx" RedirectMode="ResponseRewrite"/>

As a different solution, you can also do this in Global.asax:

void Application_Error(object sender, EventArgs e)
{
    Server.Transfer("/servererrors/AnyHTTP.aspx");
}

and on your error page, load the last error:

Exception e = Server.GetLastError();

It is important to use Server.Transfer() in the Global.asax file; using Response.Redirect will throw a 302 error and you will lose the error that you wanted to catch.

Matthew Jones
A: 

I'd recommend not using the web.config method. customErrors redirects to the error page, which makes little sense. Essentially it first says "oh yes, that'll work perfectly, you just need to go here instead", and then says "oh, we didn't find that". That's really a bug (if there isn't anything here, then why did the server tell me to go here, clearly to the user code it looks like you the server code messed up; they went to the right URI and then you directed them to the wrong one).

Use Server.Transfer() from global.asax, set a default HTTPHandler, or set IIS to execute (not redirect to) your .aspx or other file with your implementation. If you want the same handler to manage each error, then you could, for example, do a Server.Transfer() from global.asax, but include a query string parameter about the type of error (whether simply an HTTP status code, or something more detailed), or pass information in the HttpContext.

Jon Hanna