在 web.config 內容, 如果有 customErrors 元素, 表示exception 在OnException method 之前就會已經被捕捉到, 所以 Controller.cs 內的
if( filterContext.ExceptionHandled )
永遠都是true.
if(data == null)
{
return HttpNotFound();
}
HttpNotFound() 只會回傳一個HttpNotFoundResult 物件(外加把HTTP status code設定為404), 又不是丟回錯誤例外, 當然不會轉到Error Page.
當您向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