When will the MVC ExceptionFilter and the application-level error handler be executed?

I have a special FilterAttribute filter, such as:

[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 registered it globally in the FilterConfig.cs file

 public static class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters?.Add(new ExceptionLoggingFilterAttribute()); } } 

I also have a 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) } 
  • When will the exception filter code be deleted, and when will it go directly to the global error handler in the Application_Error method? (I understand the concept of ExceptionHandled and understand that by marking this as processed in my filter, it will not then be cascaded to a global error handler).

An exception, which, as I thought, would fall into the filter - HttpException for 404, does not fall into the filter, but falls into the application error handler.

  1. I saw code examples in which people use HttpContext.Current in the global.asax.cs file to make Server.TransferRequest a concrete representation of errors. Is this the best practice? Would it be better to use the CustomErrors section in the system.web section of the web.config file?
+7
c # model-view-controller asp.net-mvc-5
source share
1 answer

The exception filter will only fall for errors that occur during execution of the ASP.NET MVC pipeline, for example. during execution of an action method:

Exceptional filters. They implement an IExceptionFilter and execute if there is an unhandled exception that occurred 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 equals one example of an exception filter.

(from: https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx )

In the case of error 404, the Action method cannot be defined, so the error is not processed in the filter.

All other errors will be handled in the Application_Error method.

Regarding the second part of your question, I would recommend the following blog post, which provides a good overview of how to set up custom error pages in a reliable way: http://benfoster.io/blog/aspnet-mvc-custom-error-pages

0
source share

All Articles