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

对于我正在开发的项目,我们正在实现的一件事是我们在一些旧的ASP.NET和MVC项目团队中编写的代码 – 一个Application_Errorexception捕获器,它将开发团队的电子邮件发送给开发团队。exception经验和最相关的细节。

这是它的外观:

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("Path: {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); } 

但是,一个“次要”问题 – 当我故意让部分代码抛出exception以便测试这种机制时……

 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代码(我在方法的第一个执行行上设置断点。)

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

将您的error handling逻辑从Application_Error抽象到其自己的函数中。 创建Web APIexceptionfilter 。

 //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. } } 

Web API中的错误不会触发Application_Error事件。 但我们可以创建一个exceptionfilter并注册它来处理错误。 另请参阅ASP.NET Web API 2中的全局error handling 。