0

I am currently implementing log4net for catching my exceptions for web api controller.

I wanted to know how could i potentially catch all errors in any action within the controller?

I did not want to go through each action ideally and add try catch if it can be helped?

Ant P
  • 24,820
  • 5
  • 68
  • 105
tjhack
  • 1,022
  • 3
  • 20
  • 43
  • For unhandled exceptions - http://stackoverflow.com/questions/1367967/log4net-log-all-unhandled-application-errors – Moti Azu Jan 05 '15 at 13:28
  • Is that question about "ASP.NET Web API"? If so, consider adding the [asp.net-web-api] tag. – Christian.K Jan 05 '15 at 13:31
  • Oh, and if so, [this](http://stackoverflow.com/q/16028919/21567) might be the answer. – Christian.K Jan 05 '15 at 13:32
  • Cheers will need to catch exceptions on the web api server ideally to aid if we have any issues on the live system. Not sure if tracing will work with this? – tjhack Jan 05 '15 at 13:49

2 Answers2

2

You need to register an IExceptionLogger

e.x.: GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new YourWebApiExceptionLogger());

Hasani Blackwell
  • 2,026
  • 1
  • 13
  • 10
1

You can implement a System.Web.Http.Filters.ActionFilterAttribute. In the OnActionExecuted you can handle your logging:

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
            if (actionExecutedContext.Response != null)
            {
              //ok
            }
            else
            {
                _logger.ErrorFormat("actionExecutedContext.Response == null will result in 500, unhandled exception"); //Add extra information here
            }
    }

Then you can add this ActionFilter as attribute to the methods you want to log.

Peter
  • 27,590
  • 8
  • 64
  • 84