问题
On my web application, I had configured my web.config file to set customerrors to ON, so here it is:
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="403" redirect="Error.aspx" />
<error statusCode="404" redirect="Error.aspx" />
</customErrors>
For explaining propouses I only captured the 403 and 404 error (and the defaultRedirect obviously). But I would like to get more details of the error on the page: Error.aspx
somehow; but not creating each page for each kind of error. Is there a way to include certain code on my error page (Error.aspx) to get the detail of what raised that error?.
PD. I'm using C#.
回答1:
Just to add to the conversation and apply what others already suggested, this is how you can use what Mun suggested showing the error in the Error.aspx page:
protected void Application_Error(object sender, EventArgs e)
{
//Get last error
Exception ex = Server.GetLastError();
ex = ex.GetBaseException();
//display error to user
Context.AddError(ex);
Server.Transfer("Error.aspx", true);
}
In the Error.aspx page put this code inside the Body tag:
<p>
<i><%= Context.Error.InnerException.Message.ToString() %></i>
</p>
回答2:
btw,have you tried using ELMAH. It is the most easy to provide excellent logging and reporting of the errors.
EDIT :- I know this is nothing to do with Error.aspx. I was just suggesting a nice way of logging and reporting exceptions.
回答3:
In most situations you can use Server.GetLastError() to retrieve the error that caused the redirection.
There is a possiblitiy that you'll get into a race condition if two errors are encountered at nearly the same time, but one person's connection is faster than the other.
回答4:
You can catch and log errors by handling the Application_Error event in Global.asax.
protected void Application_OnError(object sender, EventArgs e)
{
// Get the last error
Exception exception = Server.GetLastError();
// Do something with the error here
ErrorLogger.Log(exception);
}
For error logging, you may want to consider using something like ELMAH or Log4net.
来源:https://stackoverflow.com/questions/2472398/custom-error-handling-asp-net