它是ASP.NET MVC中的异常处理方式吗?

时间:2012-08-31 03:59:53

标签: asp.net-mvc exception-handling

我已阅读有关ASP.NET MVC中异常处理的文章。我想简要介绍一下,确保我做得对。任何人都可以发表评论。

  1. 如有必要,请在控制器操作中捕获异常。

    [HttpPost]
    public ActionResult Insert()
    {
        try
        {
    
        }
        catch
        {
            //ModelState.Error -> display error msg to the user.
        }
    }
    
  2. 覆盖" OnException"基础控制器中控制器的方法和" log"步骤1中引发的异常和其他MVC异常

  3. 在application_onerror中记录全局异常。

3 个答案:

答案 0 :(得分:2)

如果你想在你的动作中处理异常,你可以在控制器中覆盖“OnException”,如下所示:

protected override void OnException(ExceptionContext filterContext)
{
  logging or user notification code here
}

您可以将它放在BaseController类中以防止重复

答案 1 :(得分:2)

我肯定会推荐ELMaH,而不是自己编写此代码,也可以通过Log4Net为您的MVC应用程序编写代码。我个人避免任何异常处理,除非我对它有特定的功能响应。通过这种方式,我不会“吃掉”像ELMaH这样的应用程序范围的工具为我优雅处理的任何错误。

ELMaH还有很好的内置网络报告功能,还有专门针对ELMaH的第三方工具可以为您提供统计信息,例如:最常见的错误。

您可以从自定义错误重定向开始......

<customErrors defaultRedirect="~/site/error" mode="RemoteOnly">
  <error statusCode="404" redirect="~/site/notfound" />
</customErrors>

...对于知道您正在使用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);
}

...由帮助访问者获取特定错误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?

答案 2 :(得分:0)

trycatch用于预期的例外情况,即您的用户输入了文件名,但可能不存在,因此您想要抓住FileNotFoundException

对于意外的异常,请使用MvcApplication对象中的Error事件,例如

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建议您使用

进行控制器级别的execption处理
protected override void OnException(ExceptionContext filterContext)
{
   // Do logging here.
}

将代码保存在您希望捕获预期并可以处理的代码上。 “通用”错误处理只是模糊了潜在的问题,你将不得不在以后挖掘它。

相关问题