透過 Global.asax 的 Application_Error 事件攔截所有未處理例外,記錄詳細錯誤資訊並導向友善錯誤頁面,避免使用者看到技術性錯誤畫面 (黃色死機畫面)。
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");
}
<%@ 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>
protected void Page_Load(object sender, EventArgs e)
{
if (Application["LastError"] != null)
{
litError.Text = Server.HtmlEncode(Application["LastError"].ToString());
}
else
{
litError.Text = "無詳細錯誤資訊。";
}
}
<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>
// 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 });
}
完善的全域錯誤處理機制是系統穩定性與用戶體驗的最後一道防線,務必在專案初期建立並持續完善日誌與監控體系。