Reputation: 3034
I have a custom exception FilterAttribute such as the following:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class ExceptionLoggingFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext));
}
if (filterContext.ExceptionHandled)
{
return;
}
// some exception logging code (not shown)
filterContext.ExceptionHandled = true;
}
I have this registered globally in my FilterConfig.cs
public static class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters?.Add(new ExceptionLoggingFilterAttribute());
}
}
I also have an Application_Error method declared in my global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
// some exception logging code (not shown)
}
An exception that I thought would hit the filter - an HttpException for 404, does not hit the filter but does get caught in the application error handler.
Upvotes: 10
Views: 1877
Reputation: 22456
An exception filter will be hit only for errors that occur during the execution of the ASP.NET MVC pipeline, e.g. during the execution of an Action method:
Exception filters. These implement IExceptionFilter and execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline. Exception filters can be used for tasks such as logging or displaying an error page. The HandleErrorAttribute class is one example of an exception filter.
(from: https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx)
In the case of a 404 error, an Action method could not be determined, so that the error is not handled in the filter.
All other errors will be handled in the Application_Error
method.
As for the second part of your question, I'd recommend the following blog post that contains a good overview on how to set up custom error pages in a reliable way: http://benfoster.io/blog/aspnet-mvc-custom-error-pages
Upvotes: 3