简体   繁体   中英

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

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 (eg 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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM