Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 962
ChaseMedallion Avatar asked Jul 03 '13 13:07

ChaseMedallion


Video Answer


1 Answers

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

like image 169
DarrellNorton Avatar answered Oct 26 '22 15:10

DarrellNorton