Reputation: 1032
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?
Upvotes: 0
Views: 1903
Reputation: 2056
You need to register an IExceptionLogger
e.x.: GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new YourWebApiExceptionLogger());
Upvotes: 2
Reputation: 27944
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.
Upvotes: 1