好吧,我是ASP.Net MVC 5中的新手,並且在小型的already existing
項目上工作,所以請耐心等待。我發現很難理解/處理/解碼我的代碼中引發的異常。如何正確捕捉ASP.Net MVC 5項目中的視圖或甚至控制器引發的異常
這裏是例外,在項目得到處理方式:
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)
{
filterContext.ExceptionHandled = true;
Response.StatusCode = 500;
Response.StatusDescription = Constants.DISPLAYED_ERROR_MESSAGE_SHARED;
if (filterContext.Exception.GetType() == typeof(ValidationException))
{ Response.StatusDescription += Constants.ADDITIONAL_DETAIL_ERROR_MESSAGE + filterContext.Exception.Message; }
else
{ Response.StatusDescription += Constants.GENERIC_ERROR_MESSAGE; }
}
}
}
public static string DISPLAYED_ERROR_MESSAGE_SHARED = "We apologize for the inconvenience, but an error has occurred. <br />";
public static string GENERIC_ERROR_MESSAGE = "Please retry your previous action. If the issues persist, please contact the facility.";
public static string ADDITIONAL_DETAIL_ERROR_MESSAGE = "<br />Additional Details: ";
Error.cshtml
@model HandleErrorInfo
@{
Layout = "~/Views/Shared/_ErrorLayout.cshtml";
}
<h2 style="color:darkred">An Error Has Occurred</h2>
<div style="color:black; font-size:110%;">
@Html.Raw(Constants.DISPLAYED_ERROR_MESSAGE_SHARED)
<br />
@Constants.GENERIC_ERROR_MESSAGE
<br />
@if (Model.Exception.GetType() == typeof(ValidationException))
{
<div style="font-size:90%;">
@Html.Raw(Constants.ADDITIONAL_DETAIL_ERROR_MESSAGE)
@Model.Exception.Message
</div>
}
</div>
學習後,我才知道,現在任何異常控制器募集將會被上面的方法所捕獲,從而避免我們在代碼中多次使用try catch。很公平。
問題無論我的項目中發生了什麼異常。我總是看到下面的消息中的瀏覽器
調試結果 每次產生一個異常的filterContext.handled
值出來是true
,因此碼永遠不會進入onException
邏輯內並直接Error.cshtml
視圖被呈現。此外,我注意到,當我檢查filterContext.Exception
的值時,我發現異常的確切的reason/issue
。
問題1:當出現異常並且在調試過程中我看到filterContext.Exception
告訴我確切的問題時,爲什麼我在瀏覽器中看不到它。爲什麼我必須經常調試,並通過將鼠標懸停在filterContext上來檢查Exeception。
問題2:每次我調試我發現filterContext.Exceptionhandled爲true。在什麼情況下它會是假的?
問題3:錯誤地爲視圖中的屬性添加了一個HtmlHelper文本框。但與該觀點相關的模型並沒有這種屬性。現在,當我調試時,我可以看到filterContext.Exception告訴我確切的問題。但是因爲我的filterContext.Exception
已經知道我做了什麼錯誤。我無法一直顯示在我的用戶界面中,而不是一般的信息。
問題4 除了上空盤旋,並讓大家認識了我的錯誤/異常的原因,我可以從filterContet.Exception什麼好處。當代碼爲in development
和not in production
時,我無法以某種方式在UI中至少在graceful manner
中看到我的錯誤。
編輯 全球ASAX
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
,並在強大的文本 Global.asax中Application_Start
方法。CS我有這樣一行:
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
看來你exeption已經被其他行爲過濾器或類似的東西hnadled。確保您不要在您的代碼庫中的某處使用HandleErrorAttribute,只需在全局註冊它即可。 – CodeNotFound
因爲我是初學者,所以對我來說很難理解。但是我在編輯部分添加了global.asax的內容。 – Unbreakable
讓我知道我是否會在代碼中查找特定關鍵字或某些內容並將其刪除。 – Unbreakable