views:

84

answers:

3

web.config:

<customErrors mode="On" defaultRedirect="~/Foo.aspx" /> 

When Foo.aspx.cs is running, how can I know that an uncaught exception is what sent me to Foo.aspx?

A: 

if (!string.IsNullOrEmpty(Request["aspxerrorpath"])) { .... }

I'm hoping for something better?

lance
A: 
void Application_Error(object sender, EventArgs e)
{
    HttpContext ctx = HttpContext.Current;
    Exception exception = ctx.Server.GetLastError();
    ctx.Server.ClearError();
    ctx.Server.Transfer("Foo.aspx?ERROR" + exception.Message);

}

This method will fire before you go to Foo.aspx, so you can catch that you are coming from an error and not a redirect. You can then append a QueryString variable to the url so that Foo.aspx can work with that data.

Not sure what your end goal it, but if you are trying to customize error message appears based on the exception you can handle it this way.

Dustin Laine
That looks really neat, but I'm trying to understand how that answers my question?
lance
I updated it, please check it out.
Dustin Laine
GetLastError() will return null if Response.Redirect("Foo.aspx") was used to send the user to Foo.aspx? Put another way: GetLastError() only returns _unhandled_ exceptions? It only returns exceptions that .NET (and not my code) caught?
lance
@durilai Actually you don't need to add that code to the `global.asax` which has been slowly deprecated by MS. Just check the `Server.GetLastError()` method.
Paulo Santos
+2  A: 

Check the Server.GetLastError() and also check the Response.StatusCode to determine why the page has been called.

If you set the customErrors element on the web.config the defautRedirect page will only be called when an unknown state occus, that is, if you specify custom pages for status codes 404 and 403, for instance, your foo.aspx page will only be called when a different status appears.

Paulo Santos