萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 全域錯誤處理與友善錯誤頁面實作 (Global.asax)

透過 Global.asax 的 Application_Error 事件攔截所有未處理例外,記錄詳細錯誤資訊並導向友善錯誤頁面,避免使用者看到技術性錯誤畫面 (黃色死機畫面)。

1. Global.asax 實作

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError().GetBaseException(); // 取得根本例外
    
    // 1. 記錄錯誤日誌 (建議使用 log4net/Serilog/NLog)
    string errorMsg = $"發生異常頁面: {Request.Url}\n" +
                      $"異常類型: {ex.GetType().FullName}\n" +
                      $"異常訊息: {ex.Message}\n" +
                      $"堆疊追蹤: {ex.StackTrace}\n" +
                      $"來源: {ex.Source}\n" +
                      $"使用者: {User.Identity.Name}\n" +
                      $"IP: {Request.UserHostAddress}";
    
    // Log.Error(errorMsg, ex); // 實際專案請接入日誌框架
    
    // 2. 儲存至 Application 暫存 (示範用,正式環境勿用,併發會覆蓋)
    // 正式環境應存入 Session、TempData 或資料庫錯誤表
    Application["LastError"] = errorMsg; 
    
    // 3. 清除伺服器錯誤狀態,避免 IIS 顯示預設錯誤頁
    Server.ClearError();
    
    // 4. 導向自訂錯誤頁面
    Response.Redirect("~/ErrorPage/ErrorPage.aspx");
}

2. 錯誤頁面 ErrorPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ErrorPage.aspx.cs" Inherits="MyApp.ErrorPage" %>
<!DOCTYPE html>
<html>
<head>
    <title>系統發生錯誤</title>
    <style>
        body { font-family: 'Microsoft JhengHei', sans-serif; text-align: center; padding-top: 50px; background: #f5f5f5; }
        .container { max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { color: #e74c3c; }
        .details { display: none; background: #f8f9fa; padding: 15px; margin-top: 20px; text-align: left; font-family: Consolas, monospace; font-size: 12px; white-space: pre-wrap; border: 1px solid #dee2e6; border-radius: 4px; }
        button { margin-top: 20px; padding: 10px 20px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; }
    </style>
</head>
<body>
    <div class="container">
        <h1>😞 系統發生錯誤</h1>
        <p>很抱歉,系統暫時無法處理您的請求。我們已記錄此錯誤並將盡快修復。</p>
        <button type="button" onclick="toggleDetails()">顯示技術細節 (供開發人員參考)</button>
        <div id="errorDetails" class="details"><asp:Literal ID="litError" runat="server" /></div>
        <br /><br />
        <a href="javascript:history.back()">返回上一頁</a> | <a href="/">回首頁</a>
    </div>
    <script>
        function toggleDetails() {
            var d = document.getElementById('errorDetails');
            d.style.display = d.style.display === 'none' ? 'block' : 'none';
        }
    </script>
</body>
</html>

3. ErrorPage.aspx.cs 顯示錯誤詳情

protected void Page_Load(object sender, EventArgs e)
{
    if (Application["LastError"] != null)
    {
        litError.Text = Server.HtmlEncode(Application["LastError"].ToString());
    }
    else
    {
        litError.Text = "無詳細錯誤資訊。";
    }
}

進階:web.config customErrors 設定 (必要補充)

<system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="~/ErrorPage/ErrorPage.aspx">
        <error statusCode="404" redirect="~/ErrorPage/404.aspx" />
        <error statusCode="500" redirect="~/ErrorPage/ErrorPage.aspx" />
    </customErrors>
</system.web>

<!-- IIS 7+ 整合模式 -->
<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="404" />
        <remove statusCode="500" />
        <error statusCode="404" path="/ErrorPage/404.aspx" responseMode="ExecuteURL" />
        <error statusCode="500" path="/ErrorPage/ErrorPage.aspx" responseMode="ExecuteURL" />
    </httpErrors>
</system.webServer>

關鍵最佳實踐

  1. 必須接入結構化日誌框架 (Serilog, NLog, log4net),寫入檔案/資料庫/Seq/Elasticsearch,勿只存 Application 變數 (併發會覆蓋、重啟遺失)。
  2. 區分環境: Development 顯示詳細堆疊,Production 僅顯示友善訊息,詳細資訊僅限管理員 IP 或登入開發人員可見。
  3. 記錄完整上下文: Request URL、Headers、Form Data、QueryString、User Identity、Session ID、Machine Name、Process ID。
  4. 異步非阻塞寫入日誌,避免錯誤處理本身拖慢回應或造成次生故障。
  5. 監控告警: 關鍵例外 (DB 連線失敗、第三方 API 逾時) 整合監控系統 (Application Insights, Datadog, Prometheus+Grafana) 發送告警。

ASP.NET Core 現代做法

// Program.cs / Startup.cs
app.UseExceptionHandler("/Error"); // 生產環境
app.UseDeveloperExceptionPage();   // 開發環境

// 錯誤頁面 Controller
[Route("/Error")]
[AllowAnonymous]
public IActionResult Error()
{
    var feature = HttpContext.Features.Get<IExceptionHandlerFeature>();
    var exception = feature?.Error;
    _logger.LogError(exception, "Unhandled exception");
    return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

完善的全域錯誤處理機制是系統穩定性與用戶體驗的最後一道防線,務必在專案初期建立並持續完善日誌與監控體系。

copyright © 萬盛學電腦網 all rights reserved