How do I log ALL exceptions globally for a C# MVC4 WebAPI app?

后端 未结 5 1698
失恋的感觉
失恋的感觉 2020-11-30 16:31

Background

I am developing an API Service Layer for a client and I have been requested to catch and log all errors globally.

So, while something like an un

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 17:10

    As an addition to previous answers.

    Yesterday, ASP.NET Web API 2.1 was oficially released.
    It offers another opportunity to handle exceptions globally.
    The details are given in the sample.

    Briefly, you add global exception loggers and/or global exception handler (only one).
    You add them to configuration:

    public static void Register(HttpConfiguration config)
    {
      config.MapHttpAttributeRoutes();
    
      // There can be multiple exception loggers.
      // (By default, no exception loggers are registered.)
      config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
    
      // There must be exactly one exception handler.
      // (There is a default one that may be replaced.)
      config.Services.Replace(typeof(IExceptionHandler), new GenericTextExceptionHandler());
    }
    

    And their realization:

    public class ElmahExceptionLogger : ExceptionLogger
    {
      public override void Log(ExceptionLoggerContext context)
      {
        ...
      }
    }
    
    public class GenericTextExceptionHandler : ExceptionHandler
    {
      public override void Handle(ExceptionHandlerContext context)
      {
        context.Result = new InternalServerErrorTextPlainResult(
          "An unhandled exception occurred; check the log for more information.",
          Encoding.UTF8,
          context.Request);
      }
    }
    

提交回复
热议问题