有三种方法在ASP.NET处理异常:
1. All the exceptions will catch page level.
2. All the exceptions will catch entire site level.
3. All the exceptions will catch by using "web.config" file
例子:
1.Exception在页级别处理。
public void Page_Error(object obj, EventArgs ergs)
{
Exception objErr = Server.GetLastError().GetBaseException();
string err = "Error Caught in Application_Error event " +
System.Environment.NewLine + "Error in: " + Request.Url.ToString() +
System.Environment.NewLine + "Error Occured Time:" + DateTime.Now +
System.Environment.NewLine + "Error Message:" + objErr.Message.ToString() +
System.Environment.NewLine + "Stack Trace:" + objErr.StackTrace.ToString();
Response.Write(err);
Server.ClearError();
Response.Redirect("~/customError.aspx");
}
2.Exception处理在网站级别。通过使用web.config文件在网站级别
protected void Application_Error(object sender, EventArgs e)
{
Exception objErr = Server.GetLastError().GetBaseException();
TraceExceptions objExceptionInsert = new TraceExceptions();
objExceptionInsert.StackTrace = objErr.StackTrace;
objExceptionInsert.Exception = objErr.Message;
objExceptionInsert.Page = Request.Url.AbsolutePath;
//Inserting exception into the database
int exceptioncode = Utilities.TraceException(objExceptionInsert);
Server.ClearError();
//Redirecting to common exception page
string url = "~/Common/Exceptions.aspx?ExceptionCode=" + exceptioncode;
Response.Redirect(url);
}
3.Exception处理。
web.config文件的customErrors元素是针对未处理错误的最后一道防线。如果你有其他错误处理程序,比如Page_Error subs的Application_Error,它们将首先被调用。如果他们没有执行Response.Redirect或Server.ClearError,则应该将其带入web.config中定义的页面。在web.config文件中,您可以处理特定的错误代码(500,404等),或者您可以使用一个页面来处理所有错误。这是此方法与其他方法之间的主要区别(尽管您可以通过使用其他方法执行各种Response.Redirects来模拟此方法)。打开你的web.config文件。该部分的customErrors使用这种格式:
<customErrors defaultRedirect="url" mode="On|Off|RemoteOnly">
<error statusCode="statuscode" redirect="url"/>
</customErrors>
这里是关于的“mode”属性的一些重要信息: “开”指定自定义错误被启用。如果没有指定defaultRedirect,用户将看到一个通用错误。
“关”指定自定义错误被禁用。这允许显示详细的错误。
“RemoteOnly”指定自定义错误仅显示给远程客户端,而ASP.NET错误显示给本地主机。这是默认设置。
默认情况下,创建Web应用程序时,该部分看起来像这样。
<customErrors mode="RemoteOnly"
是的,最后可能会有用,虽然在上面的代码中,using语句将处理任何需要关闭的db连接 –