我读过关于ASP.NET MVC中的异常处理的文章。我想通过简单的介绍来确保我做的是对的。有谁能评论一下。
发布于 2012-08-31 04:32:06
我肯定会推荐ELMaH,而不是自己编写这段代码,也不推荐您的MVC应用程序使用Log4Net。我个人避免任何异常处理,除非我有一个特定的功能反应。这样,我就不会“吃掉”应用程序工具(如ELMaH )为我处理的任何错误。
ELMaH也有不错的内置web报告,并且有专门为ELMaH提供统计信息的第三方工具,例如最常见的错误。
您可能会从自定义错误重定向开始..。
<customErrors defaultRedirect="~/site/error" mode="RemoteOnly">
<error statusCode="404" redirect="~/site/notfound" />
</customErrors>...to是一个控制器,它知道你在使用ELMaH.
public virtual ActionResult Error() {
System.Collections.IList errorList = new System.Collections.ArrayList();
ErrorLog.GetDefault(System.Web.HttpContext.Current).GetErrors(0, 1, errorList);
ErrorLogEntry entry = null;
if (errorList.Count > 0) {
entry = errorList[0] as Elmah.ErrorLogEntry;
}
return View(entry);
}...backed通过一个视图帮助访问者获得特定的错误ID:
@model Elmah.ErrorLogEntry
@if (Context.User.Identity.IsAuthenticated) {
<p>Since you are signed in, we've noted your contact information,
and may follow up regarding this to help improve our product.</p>
} else {
<p>Since you aren't signed in, we won't contact you regarding this.</p>
}
<p>Error ID: @Model.Id</p>我还注意到在本例中这是一个HttpPost。如果您正在执行AJAX,那么您将希望以一种独特的方式处理这些错误。选择一个标准响应,您可以将其发送到所有AJAX代码都能优雅处理的浏览器。也许通过在javascript警报中显示ELMaH错误ID (作为一个简单的例子)。
我还通过Global.asax处理了一些特殊类型的AJAX错误:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 302 &&
Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")HandleErrorAttribute是一个不错的特性,但众所周知,与ELMaH一起使用它需要额外的工作。How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?
发布于 2012-08-31 04:20:05
如果要在操作中处理异常,可以在Controller中覆盖"OnException“,如下所示:
protected override void OnException(ExceptionContext filterContext)
{
logging or user notification code here
}您可以将其放入您的BaseController类中以防止重复。
发布于 2012-09-05 14:08:00
try和catch用于预期的异常,即您的用户输入了一个文件名,并且它可能不存在,因此您希望捕获FileNotFoundException。
对于意外异常,请使用MvcApplication对象中的错误事件。
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
this.Error += MvcApplication_Error;
// Other code
}
private void MvcApplication_Error(object sender, EventArgs e)
{
Exception exception = this.Server.GetLastError();
// Do logging here.
}
}或者,正如Dima建议的那样,您可以使用
protected override void OnException(ExceptionContext filterContext)
{
// Do logging here.
}将尝试和捕获保存在您想要捕获的并且能够处理的代码中。“泛型”错误处理只是混淆了潜在的问题,您将不得不在后面进行挖掘。
https://stackoverflow.com/questions/12208715
复制相似问题