I'm trying to error out more gracefully when a user attempts to upload a file that's too large for the server. However, when I try to capture the error in Global.asax.cs, it seems to skip right past my redirection code. Here's the core of what I have.
protected void Application_Error(object sender, EventArgs e)
{
HttpContext.Current.ClearError();
Response.Redirect("CustomErrors.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
Everywhere I look the 'answer' seems to be to clear the error, but I've already done that. What else could possibly be going wrong. Any ideas?
I've just tried your code and when I raise an unhandled error in
Page_Load()
of my test page and then attempt to redirect withHttpContext.Current.ClearError()
present in theApplication_Error()
method I receive aRemoving this
ClearError()
method, solves this problem.If however, I raise the event within an event on the page (i.e. a button click), this works fine even with calling
HttpContent.Current.ClearError()
.One thing I did notice is you haven't got a '~/' in front of the 'CustomError.aspx', you may want to add this so that the page is found regardless of where the error is raised. (I think I you had multiple folders and an error happens, the context will be in the current folder).
A better way of adding a custom error page is just to modify the web.config with the necessary configuration, this will perform the redirect for you. You can still then log the error (via Log4Net or equivalent) in the
Application_Error()
method. You may find this question, helpful if you want to display the exception on your custom error page.From this link