捕捉的ASP.NET Web API的所有未处理的异常 [英] catch all unhandled exceptions in ASP.NET Web Api

查看:374
本文介绍了捕捉的ASP.NET Web API的所有未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何赶上的所有的发生在的ASP.NET Web API,以便我可以登录他们的未处理的异常?

How do I catch all unhandled exceptions that occur in ASP.NET Web Api so that I can log them?

到目前为止,我曾尝试:

So far I have tried:


  • 创建并注册一个<一个href=\"http://weblogs.asp.net/fredriknormen/archive/2012/06/11/asp-net-web-api-exception-handling.aspx\"><$c$c>ExceptionHandlingAttribute

  • 实施的的Application_Error 方法的Global.asax.cs

  • 订阅 AppDomain.CurrentDomain.UnhandledException

  • 订阅 TaskScheduler.UnobservedTaskException

  • Create and register an ExceptionHandlingAttribute
  • Implement an Application_Error method in Global.asax.cs
  • Subscribe to AppDomain.CurrentDomain.UnhandledException
  • Subscribe to TaskScheduler.UnobservedTaskException

ExceptionHandlingAttribute 成功地处理在控制器的操作方法和行动的过滤器中抛出的异常,但其他异常不处理,例如:

The ExceptionHandlingAttribute successfully handles exceptions that are thrown within controller action methods and action filters, but other exceptions are not handled, for example:


    的IQueryable 由操作方法返回无法执行
  • 抛出异常

  • 将一个消息处理程序抛出的异常(即 HttpConfiguration.MessageHandlers

  • 例外创建一个控制器实例时抛出

  • Exceptions thrown when an IQueryable returned by an action method fails to execute
  • Exceptions thrown by a message handler (i.e. HttpConfiguration.MessageHandlers)
  • Exceptions thrown when creating a controller instance

基本上,如果一个异常将导致500内部服务器错误被返回到客户端,我希望它记录下来。实施的Application_Error 做这件事以及在Web Forms和MVC - 我能在网页API使用

Basically, if an exception is going to cause a 500 Internal Server Error to be returned to the client, I want it logged. Implementing Application_Error did this job well in Web Forms and MVC - what can I use in Web Api?

推荐答案

这是现在可能有2.1的WebAPI(请参阅<一个href=\"http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#global-error\">What's新):

This is now possible with WebAPI 2.1 (see the What's New):

创建IExceptionLogger的一个或多个实现。例如:

Create one or more implementations of IExceptionLogger. For example:

public class TraceExceptionLogger : ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        Trace.TraceError(context.ExceptionContext.Exception.ToString());
    }
}

然后用你的应用程序的HttpConfiguration注册,一个配置回调像这样里面:

Then register with your application's HttpConfiguration, inside a config callback like so:

config.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

或者直接:

GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

这篇关于捕捉的ASP.NET Web API的所有未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆