ASP.NET Core MVC Interview Question #95

What is an exception filter?

Advanced Routing, Filters, Areas & Application Structure Mid-Level Intermediate

Quick Interview Answer

An exception filter can observe or handle unhandled exceptions that occur during parts of MVC action processing. It can convert an exception into an MVC result by marking the exception as handled.

Detailed Explanation

An exception filter can observe or handle unhandled exceptions that occur during parts of MVC action processing. It can convert an exception into an MVC result by marking the exception as handled.

For broad application-wide exception handling, ASP.NET Core exception-handling middleware is generally preferred because it covers more of the request pipeline. Exception filters are useful when exception handling specifically needs MVC context.

Code Example

public void OnException(ExceptionContext context)
{
    if (context.Exception is DomainException)
    {
        context.Result = new ViewResult
        {
            ViewName = "DomainError"
        };
        context.ExceptionHandled = true;
    }
}