简体   繁体   中英

ExceptionFilter OnException not being called

I am new at using exceptionfilters.

Following the link: https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling#httpresponserexception

I've created a class

public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotImplementedException)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}

then i used the attribute on a single method on my controller. i did not add the filter globally yet because i want it to work on a single method for now.

public class HomeController : Controller
{
    [NotImplExceptionFilter]
    public void Test()
    {
        throw new NotImplementedException("This method is not implemented");
    }
}

But the OnExepction is not being called every time i'm throwing an error. please let me know what am i missing

I think your problem is you are inheriting from Controller class instead ApiController as documentation says.

Since you are using System.Web.Http namespace in this attribute it works only for Api controllers.

If you want to use other controllers as well you need to add another exception filter attribute but in that case dont use System.Web.Http but use System.Web.Mvc namespace and the other part will be almost the same code( only a few small changes )

Override OnException again and make your logic in there but remember these two ways are different in how you actually show the error message to the user. First one use the response to show the message and the other one has to be implemented in a different way. Probably look at this one here

Your other problem is that you are missing the System.Web.Mvc.FilterAttribute, once you apply that, it should trigger as expected. (providing you make the change of using IExceptionFilter/ExceptionContext instead of ExceptionFilterAttribute/HttpActionExecutedContext as has already stated.

Example:

[AttributeUsage(AttributeTargets.Method]
    public class NotImplExceptionFilterAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext) {
        {
            if (filterContext.Exception is NotImplementedException)
        {
            filterContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM