global.asax中的Application_Error未捕获WebAPI中的错误

And*_*ray 35 .net c# asp.net error-reporting asp.net-web-api

对于我正在开发的项目,我们正在实现的一件事是我们的一些团队的旧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);
}
Run Code Online (Sandbox Code Playgroud)

但是,一个"次要"问题 - 当我故意让部分代码抛出异常以便测试这种机制时......

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
}
Run Code Online (Sandbox Code Playgroud)

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

问题:我可以通过什么方式让"旧" Application_Error处理程序发送错误电子邮件,以便我们团队的开发人员可以更轻松地调试我们的应用程序?

mas*_*son 62

将错误处理逻辑Application_Error从其自身功能中抽象出来.创建Web API异常过滤器.

//register your filter with Web API pipeline
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.
    }
}
Run Code Online (Sandbox Code Playgroud)

Web API中的错误不会触发Application_Error事件.但是我们可以创建一个异常过滤器并注册它来处理错误.另请参阅ASP.NET Web API 2中的全局错误处理.

  • @LeandroDeMelloFagundes当Web API出现异常时,不会触发Application_Error事件.您可能已经登录Application_Error来处理ASP.NET异常.因此,将该逻辑放在可以从Application_Error或应用于Web API操作方法的异常过滤器中使用的公共服务中遵循DRY原则.没有重复的逻辑. (4认同)
  • LOL打电话给消防部门:-) :-) (4认同)