ASP.NET定制简单的错误处理页面

 通常Web应用程序在发布后,为了给用户一个友好界面和使用体验,都会在错误发生时跳转至一个自定义的错误页面,而不是ASP.net向用户暴露出来的详细的异常列表。

  简单的错误处理页面可以通过web.config来设置

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> 
 <error statusCode="403" redirect="NoAccess.htm" /> 
 <error statusCode="404" redirect="FileNotFound.htm" /> 
</customErrors>

  如果想通过编程的方式来呈现错误原因,可以通过Page_Error事件来做这件事。

  另一种方式则可以通过Global.asax来实现,我觉得这种方式较为方便,另外如果能结合一个单独的更加友好的页面,则看来起更舒服一些:

  Global.asax(如果需要,可以记录错误日志)

void Application_Error(object sender, EventArgs e)  

 Exception objErr 
= Server.GetLastError().GetBaseException(); 
 
string error = "发生异常页: " + Request.Url.ToString() + "<br>"
 error 
+= "异常信息: " + objErr.Message + "<br>"
 Server.ClearError(); 
 Application[
"error"= error; 
 Response.Redirect(
"~/ErrorPage/ErrorPage.aspx"); 


ErrorPage.aspx 
protected void Page_Load(object sender, EventArgs e) 

 ErrorMessageLabel.Text 
= Application["error"].ToString(); 
}

  当最终用户使用应用程序的时候,他们可能不想知道错误的原因,这个时候,我们可以通过复选框来实现,是否呈现错误的原因。可将Label放在一个div中,然后用复选框来决定是否呈现div

<script language="JavaScript" type="text/Javascript"> 
function CheckError_onclick() { 
 
var chk = document.getElementById("CheckError"); 
 
var divError = document.getElementById("errorMsg"); 
 
if(chk.checked) 
 { 
  divError.style.display 
= "inline"
 } 
 
else 
 { 
  divError.style.display 
= "none"
 } 

 
/script>

  我们可以将errorpage页做得更漂亮些,让人看起来更舒服。

原文地址:https://www.cnblogs.com/oec2003/p/736187.html