網站面對多樣的使用者、瀏覽器、網路環境,例外狀況難以完全避免。將例外分為兩類:
// 不好:用例外處理預設值
int temp = 0;
try { temp = Int32.Parse(input); }
catch { temp = 1; }
// 好:使用 TryParse
int temp = 0;
if (!Int32.TryParse(input, out temp)) temp = 1;
建立 `BasePage : System.Web.UI.Page`,在建構子註冊 `Error` 事件:
public class BasePage : Page
{
public BasePage() { this.Error += PageBase_Error; }
protected void PageBase_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex == null) return;
LogError(ex); // 記錄日誌、發送通知
string msg = "系統發生錯誤,請稍後再試或聯繫管理員。";
#if DEBUG
msg = ex.Message + "<br/>Stack: " + ex.StackTrace;
#endif
Response.Write(msg);
// 或 Response.Redirect("Error.html"); // 靜態錯誤頁最安全
Server.ClearError();
}
protected virtual void LogError(Exception ex) { /* 實作記錄邏輯 */ }
}
所有頁面繼承 `BasePage` 即可自動套用。若專案已有大量頁面,可在 `web.config` 設定 `pageBaseType` 強制套用。
全域攔截未處理例外,適合集中記錄與導向:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex == null) return;
LogError(ex);
// 避免遞迴錯誤,導向靜態頁
Server.Transfer("~/Error.html");
// 或 Response.Redirect("~/Error.aspx?code=500");
}
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx">
<error statusCode="404" redirect="~/404.aspx" />
<error statusCode="500" redirect="~/500.aspx" />
</customErrors>
</system.web>
在 `Error.aspx` 中可讀取 `Server.GetLastError()` 並顯示友善訊息,記得呼叫 `Server.ClearError()`。