1. Global.asax 捕獲未處理異常
void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError().GetBaseException();
string errorMsg = $"時間: {DateTime.Now}\nURL: {Request.Url}\n錯誤: {ex.Message}\n堆疊: {ex.StackTrace}";
// 記錄日誌(檔案/資料庫/Serilog/ELMAH)
LogHelper.WriteError(errorMsg);
Server.ClearError(); // 必須清除,否則 ASP.NET 仍會顯示黃屏
// 導向友善錯誤頁,攜帶錯誤資訊(可用 Session/TempData)
Session["LastError"] = errorMsg;
Response.Redirect("~/Error/ErrorPage.aspx");
}
2. 友善錯誤頁面
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ErrorPage.aspx.cs" Inherits="ErrorPage" %>
<!DOCTYPE html>
<html>
<head>
<title>系統錯誤</title>
<style>
body {font-family: 'Microsoft JhengHei', sans-serif; text-align:center; padding:50px;}
.error-box {max-width:600px; margin:auto; padding:20px; border:1px solid #ddd; border-radius:8px;}
.detail {display:none; margin-top:20px; text-align:left; background:#f8f8f8; padding:15px; font-family:Consolas, monospace; font-size:12px; white-space:pre-wrap;}
</style>
</head>
<body>
<div class="error-box">
<h2>很抱歉,系統發生錯誤</h2>
<p>我們已記錄此錯誤,技術人員會盡快處理。</p>
<label><input type="checkbox" id="chkDetail" onclick="toggleDetail()" /> 顯示詳細資訊(僅供開發人員)</label>
<div id="divDetail" class="detail"><asp:Literal ID="litDetail" runat="server" /></div>
<br /><a href="/" class="btn">返回首頁</a>
</div>
<script>
function toggleDetail() {
document.getElementById('divDetail').style.display = document.getElementById('chkDetail').checked ? 'block' : 'none';
}
</script>
</body>
</html>
3. 後端綁定錯誤明細
protected void Page_Load(object sender, EventArgs e)
{
if (Session["LastError"] != null)
{
litDetail.Text = Server.HtmlEncode(Session["LastError"].ToString());
Session.Remove("LastError"); // 顯示後清除
}
}
4. web.config 設定自訂錯誤
<system.web>
<customErrors mode="On" defaultRedirect="~/Error/ErrorPage.aspx">
<error statusCode="404" redirect="~/Error/404.aspx" />
<error statusCode="500" redirect="~/Error/ErrorPage.aspx" />
</customErrors>
</system.web>
進階建議
- ELMAH:NuGet 安裝 `Elmah.Mvc`,自動記錄所有未處理異常、黃屏截圖、查詢介面,零程式碼。
- Serilog + Seq:結構化日誌、即時儀表板、告警。
- 區分環境: `customErrors mode="RemoteOnly"` 本地顯示黃屏,遠端顯示友善頁。
- AJAX 錯誤: `Application_Error` 中判斷 `Request.Headers["X-Requested-With"] == "XMLHttpRequest"` 回傳 JSON 而非導向。