通常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 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這頁做一些更親切的設計,讓人看起來更舒服些。^_^
永久地址:http://www.cnblogs.com/yoshow/archive/2007/01/18/623404.html