对于我正在工作的一个项目,我们正在实现的一件事是我们在我的团队的一些较早的ASP.NET和MVC项目中为其编写的代码-一个Application_Error异常捕获器,它向开发团队发送一封邮箱,其中包含异常经验和最相关的详细信息.

下面是它的外观:

Global.asax:

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    string path = "N/A";
    if (sender is HttpApplication)
        path = ((HttpApplication) sender).Request.Url.PathAndQuery;

    string args = string.Format("<b>Path:</b> {0}", path);

    // Custom code that generates an HTML-formatted exception dump
    string message = Email.GenerateExceptionMessage(ex, args);

    // Custom code that sends an email to the dev team.
    Email.SendUnexpectedErrorMessage("Some App", message);
}

不过有一个"小"问题——当我故意让代码的一部分抛出异常以测试这种机制时...

public static void GetMuffinsByTopping(string topping)
{
    throw new Exception("Test Exception!", new Exception("Test Inner Exception!!!"));

    // Actual repository code is unreachable while this test code is there
}

前端JavaScript立即拦截HTTP 500请求,但是没有达到上面提到的global.asax.cs代码(我在该方法的第一个执行行上设置了断点).

Question:如何让"旧"Application_Error处理程序发送错误邮箱,以便我们团队的开发人员能够更轻松地调试我们的应用程序?

推荐答案

将您的错误处理逻辑从Application_Error抽象到它自己的函数中.创建一个Web API exception filter.

//register your filter with Web API pipeline
//this belongs in the Application_Start event in Global Application Handler class (global.asax)
//or some other location that runs on startup
GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute());

//Create filter
public class LogExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        ErrorLogService.LogError(context.Exception);
    }
}

//in global.asax or global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    ErrorLogService.LogError(ex);
} 

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Email developers, call fire department, log to database etc.
    }
}

来自Web API的错误不会触发应用程序错误事件.但是我们可以创建一个异常过滤器并注册它来处理错误.另见Global Error Handling in ASP.NET Web API 2.

Asp.net相关问答推荐

禁用托管优化并重新启动调试实际上在 Visual Studio 中更改了哪些设置?

在 Web.Config 的 Location Path 元素中指定多个目录

Server.Transfer 在执行子请求时抛出错误.如何解决?

登录成功后 User.Identity.IsAuthenticated 为 false

Anti-Forgery Token 适用于不同的基于声明的用户

在 Asp.net 中通过 Button 的 CommandArgument 传递多个参数

从 IIS 7/8 中的静态内容中删除服务器标头

如何通过后面的代码不显示

从 JavaScript 读取 web.config

带有完整内存错误的 WCF 服务(内存门判断失败,因为可用内存) - 如何解决

确定哪个 w3wp.exe 进程属于 Windows 7 / IIS7.5 中的哪个 App Pool?

在 ASP.NET 中实现 404 的最佳方法

如何在 C# 应用程序中调用 VBScript 文件?

如何使用 ASP.NET 和 jQuery 返回 JSON

避免将重复元素添加到列表 C#

ASP.Net 无法创建/卷影复制

elmah:没有 HttpContext 的异常?

避免在 ASP.NET MVC 中使用会话状态是一种好习惯吗?如果是,为什么以及如何?

POST 字符串到 ASP.NET Web Api 应用程序 - 返回 null

ModelClientValidationRule 冲突