Advertisement
Advanced ASP.NET Core, Filters

How does IExceptionFilter differ from global exception handling middleware, and when would you choose one over the other?

Short answer

Exception filters run within the MVC action invocation pipeline specifically, giving access to MVC-specific context (like the ActionDescriptor and ModelState) that middleware-level exception handling doesn't have, but they only catch exceptions from within controller actions --…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Exception filters run within the MVC action invocation pipeline specifically, giving access to MVC-specific context (like the ActionDescriptor and ModelState) that middleware-level exception handling doesn't have, but they only catch exceptions from within controller actions -- not from middleware, routing, or minimal API endpoints. Global exception handling middleware (UseExceptionHandler/IExceptionHandler) catches exceptions from the entire pipeline uniformly, making it the more comprehensive, generally-preferred approach, with exception filters reserved for MVC-specific scenarios needing that extra action context.
public class MvcSpecificExceptionFilter : IExceptionFilter {
    public void OnException(ExceptionContext context) {
        if (context.Exception is ValidationException ve) {
            context.Result = new BadRequestObjectResult(new { errors = ve.Errors, action = context.ActionDescriptor.DisplayName });
            context.ExceptionHandled = true;
        }
    }
}
Real-world example
A team uses global exception handling middleware as their primary, comprehensive error-handling mechanism, reserving a narrow exception filter only for one specific controller needing access to MVC action metadata unavailable at the middleware level.
Likely follow-ups
  • Why can't exception filters catch exceptions from middleware or minimal API endpoints?
  • What's the recommended default choice for a new project starting from scratch?
Related topics