Reputation: 33
I am new at using exceptionfilters.
Following the link: https://learn.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
Upvotes: 1
Views: 3228
Reputation: 1673
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);
}
}
}
Upvotes: 0
Reputation: 4002
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
Upvotes: 2