6

I have a custom exception filter capable handle all the errors in the controller( just a common error handling mechanism) ,

public class ExceptionHandlingAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            var error = actionExecutedContext.Exception;
            if (error is BussinessExcetion)
            {
                var exceptionBase = (BussinessExcetion)error;
                var code = (HttpStatusCode)exceptionBase.HttpExceptionCode;
                throw new HttpResponseException(new HttpResponseMessage(code)
                                                    {
                                                        Content = new StringContent(exceptionBase.Message),
                                                        ReasonPhrase = "Exception"

                                                        ,
                                                    });

            }

            // Now log the error

            /* Error logging */

            LoggingFactory.GetLogger().LogError(string.Format("Exception:{0} ||Stack trace:{1}", error.Message, error.StackTrace), error);



            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                                                {
                                                    Content = new StringContent("An error occurred, contact the support team."),
                                                    ReasonPhrase = "Critical Exception"
                                                });
        }
    }

I registered this filter in fillterConfig file

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ExceptionHandlingAttribute());
     filters.Add(new HandleErrorAttribute());

    }

but i am getting an error

The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter

I know the ExceptionFilterAttribute already implimented IExceptionFilter filter. Why i am getting this error

3
  • becouse your filter class must be inherit of IExceptionFilter interface Commented Feb 1, 2014 at 4:24
  • 7
    Solved.. The problem was i am registering filter in FilterConfig file . this for MVC not for web api . i changed the registration in to WebApiConfig file Commented Feb 1, 2014 at 4:36
  • 1
    You should make this comment into an answer. Commented Nov 24, 2014 at 10:08

3 Answers 3

6

In order for this to work, you need to implement System.Web.Http.Filters.ExceptionFilterAttribute.

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
    log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public override void OnException(HttpActionExecutedContext context)
    {
        RequestData requestData = new RequestData(context.Request);

        log.Error("NotImplExceptionFilterAttribute", context.Exception);
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
    }
}

Then, in your WebApiConfig.cs, register the filter:

public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{count}",
            defaults: new { count = RouteParameter.Optional }
        );

        config.Filters.Add(new NotImplExceptionFilterAttribute());
    }
Sign up to request clarification or add additional context in comments.

Comments

2

make sure you also override the Async version of the filter

class myFilter : ExceptionFilterAttribute
{
...
    public override async Task OnExceptionAsync(HttpActionExecutedContext ctx, 
                                                CancellationToken cancellationToken)
    {
    ...
    }
...
}

Comments

1

And for anyone using NLog:

public class NlogExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext filterContext)
    {
        Exception lastException = filterContext.Exception;
        Logger logger = LogManager.GetLogger("");
        logger.Fatal(lastException.Message, lastException);
    }
}

And in the WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new NlogExceptionFilter());
    ...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.