如何为所有其他运行时错误添加通用错误页
本文关键字:添加 错误 运行时错误 其他 | 更新日期: 2023-09-27 17:54:36
我正在尝试调整
<customErrors mode="On" defaultRedirect ="~/System/err.aspx">
</customErrors>
web。配置文件
因此,无论何时在任何页面中出现运行时错误或任何类型错误,错误消息都不应显示在该页面上,而应将其重定向到err。aspx页面。
是否存在这样的配置?
(1)您采用的方法是正确的。您需要为不同类型的错误指定不同的错误页面(如果您想以不同的方式处理不同的错误类型),就像nadeem提到的,
(2)第二种方法是在全局中使用Application_Error。如下所示:
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>'n");
Response.Write(
"<p>" + exc.Message + "</p>'n");
Response.Write("Return to the <a href='Default.aspx'>" +
"Default Page</a>'n");
// Clear the error from the server
Server.ClearError();
}
(3)第三种方法是同时使用Application_Error和自定义错误页面。使用Application_Error获取异常详细信息,并将其传递给错误页面,如
protected void Application_Error(object sender, EventArgs e)
{
Exception err = Server.GetLastError();
Session.Add("LastError", err);
}
void Session_Start(object sender, EventArgs e)
{
Session["LastError"] = ""; //initialize the session
}
错误页:
protected void Page_Load(object sender, EventArgs e)
{
Exception err = Session["LastError"] as Exception;
//Exception err = Server.GetLastError();
if (err != null)
{
err = err.GetBaseException();
lblErrorMsg.Text = err.Message;
lblSource.Text = err.Source;
lblInnerEx.Text = (err.InnerException != null) ? err.InnerException.ToString() : "";
lblStackTrace.Text = err.StackTrace;
Session["LastError"] = null;
}
}
网站上有很多链接可以帮你解决这个问题,因此,如果你没有找到,请参阅下面的代码。您需要在
下面添加如下代码 configuration
section。还有一个名为err
的页面,上面的所有信息都清楚地表明这是一个错误页面。
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="err.aspx">
<error statusCode="404" redirect="404.aspx" />
<error statusCode="500" redirect="500.aspx" />
</customErrors>
</system.web>
也可以看一下这里的一个例子来清楚地理解
希望有帮助
我们更喜欢在Global中捕获这些。在重定向到错误页面之前,我们可以做一些自定义的异常处理,如写入事件日志,保存到数据库和电子邮件支持人员。
Global.asax.cs;
void Application_Error(object sender, EventArgs e)
{
// Get the exception
Exception exc = Server.GetLastError();
// Do something with the exception, write it to the event log, save it to the db, email someone who cares etc
// Clear the error
Server.ClearError();
// Redirect to a generic error page
Response.Redirect("~/System/err.aspx");
}
进一步的用法示例如下:https://msdn.microsoft.com/en-us/library/24395wz3 (v = vs.140) . aspx