好吧,我是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