Custom error handling Asp.Net

自作多情 提交于 2020-01-24 09:05:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!