In an ASP.NET Core MVC payroll back office, how would an exception filter translate domain exceptions into HTTP responses, and what can it not catch?
answer
- IExceptionFilter.OnException(ExceptionContext)
- set Result and ExceptionHandled
- handled with no Result means empty 200
- innermost filter sees it first
- result execution is out of reach
basics
~10 sImplement IExceptionFilter, check context.Exception for a domain type such as PayrollPeriodClosedException, set context.Result to a 409 ProblemDetails and ExceptionHandled = true. It cannot catch exceptions from resource filters, result filters or result execution.
solid answer
~40 sAn exception filter (`IExceptionFilter` or `IAsyncExceptionFilter`, or a subclass of `ExceptionFilterAttribute`) runs when controller creation, model binding, an action filter or the action throws. In `OnException` you inspect `context.Exception`; for a domain type you know, you set `context.Result`, for example an `ObjectResult` holding a 409 `ProblemDetails`, and set `context.ExceptionHandled = true`. Leave unknown exceptions alone so middleware logs and handles them. Exception filters unwind from the innermost one outward, and an outer filter skips an exception that is already handled. Watch two traps: setting `ExceptionHandled` without a `Result` sends an empty 200 through `EmptyResult`, and exceptions thrown while a view renders or a formatter serializes, or inside resource and result filters, never reach the filter. App-wide handling belongs in `UseExceptionHandler` with an `IExceptionHandler`; a filter fits where translation differs per controller.
code
csharp · 13 lines[ApiController]
[Route("api/admin/payroll/periods")]
[TypeFilter(typeof(PayrollExceptionFilter))]
public class PayrollPeriodsController(IPayrollService payroll) : ControllerBase
{
[HttpPut("{periodId:int}/lines/{lineId:int}")]
public async Task<IActionResult> UpdateLine(int periodId, int lineId, PayLineUpdate update, CancellationToken ct)
{
// throws PayrollPeriodClosedException for a locked period
await payroll.UpdateLineAsync(periodId, lineId, update, ct);
return NoContent();
}
}go deeper
Recall that an exception filter implements OnException, inspects context.Exception and sets a Result to turn it into a response.
Explain the filter's reach, the inner-to-outer unwinding, why ExceptionHandled without a Result is an empty 200, and which result filters still run.
Combine a narrow per-controller translation filter with middleware as the catch-all, and make sure unknown exceptions still reach logging.
Define the domain-exception-to-status contract once for the platform so every API and screen answers the same failure the same way.
## The problem The payroll domain throws meaningful exceptions: `PayrollPeriodClosedException` when an admin edits a locked period, `PayRunAlreadyApprovedException` on a double approval, `TaxCodeNotFoundException` for an unknown code. Letting them escape produces a generic 500; catching them in every action clutters controllers. An **exception filter** translates them in one place, for the controllers that want that translation. ## Writing the filter ```csharp public sealed class PayrollExceptionFilter(ProblemDetailsFactory problems) : IExceptionFilter { public void OnException(ExceptionContext context) { var status = context.Exception switch { PayrollPeriodClosedException => StatusCodes.Status409Conflict, PayRunAlreadyApprovedException => StatusCodes.Status409Conflict, TaxCodeNotFoundException => StatusCodes.Status404NotFound, _ => (int?)null }; if (status is null) return; // not ours: let it propagate var body = problems.CreateProblemDetails(context.HttpContext, status.Value, detail: context.Exception.Message); context.Result = new ObjectResult(body) { StatusCode = status }; context.ExceptionHandled = true; } } ``` Apply it with `[TypeFilter(typeof(PayrollExceptionFilter))]` on the payroll controllers, or globally with `o.Filters.Add<PayrollExceptionFilter>()`. ## What it catches and what it doesn't In the source, the exception-filter scope wraps controller creation, argument binding, the action filters and the action. Everything else is outside it: | Thrown in | Reaches exception filters? | |---|---| | Controller constructor or model binding | yes | | An action filter | yes | | The action method | yes | | A resource filter | no | | A result filter, or while executing the result (rendering a view, serializing JSON) | no | | Middleware, routing | no | The docs' overview list of filter types says otherwise for model binding and result execution; their own exception-filter section and the invoker's code agree with the table. ## Handling rules from the invoker 1. **Unwinding order.** Exception filters nest like the other kinds, so on the way out the innermost one (action scope, or the highest `Order`) sees the exception first, then the controller-scoped one, then global ones. 2. **Once handled, outer filters skip it.** Each filter runs only if `Exception` is not null and `ExceptionHandled` is false. A global catch-all therefore only sees what the specific filters left. 3. **Setting `Result` alone also stops propagation**, but outer filters still run because `ExceptionHandled` is false, and they may overwrite your result. Set both. 4. **`ExceptionHandled = true` without a `Result`** makes MVC use an `EmptyResult`: the client gets a 200 with an empty body. That is the most common bug in hand-written exception filters. 5. After an exception filter handles the exception, only `IAlwaysRunResultFilter` result filters run; ordinary result filters are skipped. ## Async, attribute and logging variants - `IAsyncExceptionFilter.OnExceptionAsync` suits translation that needs I/O, such as looking up a localized message; implement one interface, not both. - `ExceptionFilterAttribute` is an abstract base with both methods and an `Order` property, convenient for `[PayrollExceptions]` on a controller, but its constructor cannot take services, so a filter needing `ProblemDetailsFactory` or a logger is applied with `[TypeFilter]` or `[ServiceFilter]` instead. - A handled exception is no longer seen by the exception-handling middleware, so it is not logged there. If a translated domain exception still deserves a log line, write it in the filter, at a level that matches: a closed payroll period is a client mistake (Information or Warning), not an Error. ## Exception filter or exception-handling middleware? - **Middleware** (`UseExceptionHandler` with `IExceptionHandler` implementations) sees exceptions from the whole app, including result execution, other middleware and Minimal APIs. The docs recommend it as the default. - **Exception filters** fit when the translation depends on the controller or action: the payroll API returns ProblemDetails while the HTML admin screens show an error view, or one area maps `TaxCodeNotFoundException` to 404 and another to 422. - Many apps combine them: middleware is the catch-all, and a narrow filter turns known domain exceptions into specific statuses where the action context matters. ## Testing it Construct an `ExceptionContext` from an `ActionContext` with a `DefaultHttpContext`, an empty `RouteData` and an `ActionDescriptor`, plus an empty filter list; call `OnException` and assert on `Result` and `ExceptionHandled`. Cover the "not ours" branch too: the filter must leave `ExceptionHandled` false for an unknown exception.
- Why does the client get an empty 200 after your exception filter runs?The filter set `ExceptionHandled = true` but left `Result` null. MVC treats the exception as handled and substitutes an `EmptyResult`, and the response keeps its default 200 status. Always assign a result with an explicit status when you mark an exception handled.
- A JSON serializer exception during response writing is not translated by the filter. Why?Serialization happens while the `ObjectResult` executes, which is outside the exception-filter scope. Only result filters and the middleware above MVC can observe it, and by then the response may have started, so handle it in `UseExceptionHandler`.
- Setting ExceptionHandled = true is enough; MVC then returns a 500 for you.
- Exception filters also catch errors thrown while rendering a view.
- A global exception filter always runs, even after an action-level one handled the exception.
- An exception filter should catch every exception type and return a 400.
- Exception filters replace the need for exception-handling middleware.