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?

4
  • For unhandled exceptions - stackoverflow.com/questions/1367967/… Commented Jan 5, 2015 at 13:28
  • Is that question about "ASP.NET Web API"? If so, consider adding the [asp.net-web-api] tag. Commented Jan 5, 2015 at 13:31
  • Oh, and if so, this might be the answer. Commented Jan 5, 2015 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? Commented Jan 5, 2015 at 13:49

2 Answers 2

2

You need to register an IExceptionLogger

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.