How do I set up a global error handler in WebApi?

2020-06-18 03:14发布

问题:

I am building a .NET WebApi application and I would like to set up a global error handler (basically a function that executes when an exception bubbles up from anywhere in the application). this link laments support for this, but several workarounds are offered. Unfortunately, I can't seem to find useful documentation for any of them.

Here are my requirements:

  • Catch exceptions hit in action methods as well as in other places (e. g. controller resolution).
  • Have access to the original Exception object during my handling.
  • Have access to services in my (Autofac) IOC container during the error handling process (this is a strong want but not a must have).
  • No dependency on MVC (I am using pure WebApi). No dependency on IIS is highly desirable.

How do I go about setting this up?

回答1:

If you update to Web API v2.1, available via Nuget with this command:

Install-Package Microsoft.AspNet.WebApi

You can create a Global Exception Handler by inheriting from Exception Logger.

Here is an example:

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

More details in the release notes here: http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#global-error



回答2:

There are a few options you should be aware of:

Event AppDomain.CurrentDomain.FirstChanceException:

Will fire for every exception no matter if it is handled. Use this for logging etc before your specific handler.

Event AppDomain.CurrentDomain.UnhandledException:

Will Fire for every exception not handled in code

You would need to create handler in a service that has access to your IOC container etc