Skip to content

Instantly share code, notes, and snippets.

@flashlin
Last active August 18, 2020 04:59
Show Gist options
  • Save flashlin/94624b066eb93f0b4c6c349b3a3f59e4 to your computer and use it in GitHub Desktop.
Save flashlin/94624b066eb93f0b4c6c349b3a3f59e4 to your computer and use it in GitHub Desktop.
Global Error Handle #aspnet #errorHandle

理想情況下, 對於錯誤頁面, 應該終使用簡單的靜態檔案.

注意的是Override OnException method inside the Controller , 這方法會先判斷Exception 是否有沒有被處理.

在 web.config 內容, 如果有 customErrors 元素, 表示exception 在OnException method 之前就會已經被捕捉到, 所以 Controller.cs 內的

if( filterContext.ExceptionHandled ) 

永遠都是true.

另外Controller 常常可以看到類似這樣一段程式

if(data == null)
{
  return HttpNotFound();
}

HttpNotFound() 只會回傳一個HttpNotFoundResult 物件(外加把HTTP status code設定為404), 又不是丟回錯誤例外, 當然不會轉到Error Page.

[HandleError] Attribute

當您向Controller 提供[HandleError] 屬性時, 則當發生未能處理的異常時, MVC 將首先在Controller 的View 資料夾中查找名為 "Error" 的對應視圖. 如果找不到該檔案, 它將繼續在 "Shared Views" 資料夾中查找. (預設情況下, 該資料夾中應具有Error.aspx 檔案)

[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")]
public class MyConctroller : Controller {
}

您還可以將其他屬性與有關您要查找的異常類型的特定信息堆疊在一起.

HandleError 特性是依賴自定義錯誤的, customErrors的Model 必須要設置為On 或RemoteOnly

<asp:Content ID="errorContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%= Html.Encode(ViewData["Title"]) %></h2>
<p><%= Html.Encode(ViewData["Description"])%></p>
<div>
<%= Html.ActionLink("返回首頁", "Index", "Home") %>.
</div>
</asp:Content>
public class ErrorController : Controller
{
public ActionResult General(string error)
{
ViewData["Title"] = "抱歉, 處理你的請求發生錯誤";
ViewData["Description"] = error;
return View("Error");
}
}
protected void Application_Error(object sender, EventArgs e)
{
var unhandledException = Server.GetLastError();
Response.Clear();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
var errorMsg = Request.Path + Environment.NewLine +
unhandledException.GetBaseException().Message + Environment.NewLine +
unhandledException.StackTrace + Environment.NewLine;
EventLog.WriteEntry("WebError", errorMsg, EventLogEntryType.Error);
routeData.Values.Add("action", "General");
routeData.Values.Add("Error", unhandledException);
Server.ClearError();
IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<system.web>
<customErrors mode="On" defaultRedirect="/Error/Index" xdt:Transform="Replace" />
</system.web>
<configuration>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment