ASP.NET custom simple error handling page implementation code

  • 2020-05-07 19:30:53
  • OfStack

The simple error handling page can be set with web.config.
 
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> 
 <error statusCode="403" redirect="NoAccess.htm" /> 
 <error statusCode="404" redirect="FileNotFound.htm" /> 
</customErrors> 

If you want to present the cause of the error programmatically, you can do so with the Page_Error event.
Another way can be realized by Global.asax, which I think is more convenient. In addition, if you can combine a single page with a more friendly one, it will be more comfortable:
Global.asax (error logging if required)
 
void Application_Error(object sender, EventArgs e) 
{ 
 Exception objErr = Server.GetLastError().GetBaseException(); 
 string error = " Abnormal page : " + Request.Url.ToString() + "<br>"; 
 error += " Exception information : " + 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(); 
} 

When the end user USES the application, they may not want to know the cause of the error, at which point we can check the box to see if the cause of the error is rendered. You can put Label in one div and use the check box to decide whether to render 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> 

Related articles: