asp.net-mvc - 记录 ASP.NET MVC 中的错误

标签 asp.net-mvc error-handling

我目前在 ASP.NET MVC 应用程序中使用 log4net 来记录异常。我这样做的方法是让所有 Controller 继承自 BaseController 类。在 BaseController 的 OnActionExecuting 事件中,我记录了可能发生的任何异常:

protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    // Log any exceptions
    ILog log = LogManager.GetLogger(filterContext.Controller.GetType());

    if (filterContext.Exception != null)
    {
        log.Error("Unhandled exception: " + filterContext.Exception.Message +
            ". Stack trace: " + filterContext.Exception.StackTrace, 
            filterContext.Exception);
    }
}

如果在 Controller 操作期间发生未处理的异常,这非常有效。

对于 404 错误,我在 web.config 中设置了一个自定义错误,如下所示:

<customErrors mode="On">
    <error statusCode="404" redirect="~/page-not-found"/>
</customErrors>

在处理“page-not-found”网址的 Controller 操作中,我记录了所请求的原始网址:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult PageNotFound()
{
    log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));

    return View();
}

这也有效。

我遇到的问题是如何记录 .aspx 页面本身的错误。假设我在其中一个页面上出现编译错误,或者某些内联代码会引发异常:

<% ThisIsNotAValidFunction(); %>
<% throw new Exception("help!"); %>

看起来 HandleError 属性正确地将其重新路由到共享文件夹中的 Error.aspx 页面,但它绝对没有被我的 BaseController 的 OnActionExecuted 方法捕获。我想我也许可以将日志记录代码放在 Error.aspx 页面本身上,但我不确定如何检索该级别的错误信息。

最佳答案

我会考虑通过插入 Elmah 来简化您的 Web 应用程序.

您将 Elmah 程序集添加到您的项目中,然后配置您的 web.config。然后它将记录在 Controller 或页面级别创建的异常。它可以配置为记录到各种不同的地方(如 SQL Server、电子邮件等)。它还提供了一个Web前端,以便您可以浏览异常日志。

这是我添加到我创建的任何 asp.net mvc 应用程序中的第一件事。

我仍然使用 log4net,但我倾向于使用它来记录调试/信息,并将所有异常(exception)情况留给 Elmah。

您还可以在问题 How do you log errors (Exceptions) in your ASP.NET apps? 中找到更多信息.

关于asp.net-mvc - 记录 ASP.NET MVC 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569252/

相关文章:

c++ - 使用 lambda 和宏进行错误处理有缺点吗?

asp.net - 使用 System.Net.Mail 处理 Global.cs 错误

asp.net-mvc - Knockout Js、JQuery UI 对话框和部分 View

c# - LINQ to Entities 无法识别该方法并且无法将此方法转换为存储表达式

c# - 如何解析传递给 mvc Controller 的空 json 字符串?

c# - 使用 Awesomium 捕获网络错误

php - PHP自定义错误处理程序

function - 为什么这不返回错误?

asp.net-mvc - 如何打开 Bootstrap 模式而不回发?

asp.net-mvc - ReactJs - 访问 onclick 事件中的状态