skip to content

With MediatR, how do IRequestExceptionHandler and IRequestExceptionAction differ, and in which order and for which exceptions do they run?

level: seniorimportance: nice to knowfreq 22%

answer

  1. handler may call state.SetHandled(response)
  2. action observes, exception rethrown
  3. most specific exception type first
  4. ApplyForUnhandledExceptions by default
  5. registered only if implementations exist

basics

~20 s

An IRequestExceptionHandler can turn an exception into a response with state.SetHandled(response); an IRequestExceptionAction only reacts, then the exception is rethrown. Both match from the most specific exception type up, and by default actions see only unhandled exceptions.

solid answer

~40 s

`IRequestExceptionHandler<TRequest, TResponse, TException>.Handle(request, exception, state, ct)` gets a `RequestExceptionHandlerState<TResponse>`; calling `state.SetHandled(response)` makes `Send` return that response instead of throwing. `IRequestExceptionAction<TRequest, TException>.Execute(request, exception, ct)` cannot change the outcome: every matching action runs, then the exception is rethrown. MediatR walks the exception's type hierarchy from the thrown type up to `Exception`, so specific handlers are tried first, and among equals it prefers those in the request's own assembly and namespace; the first handler that calls `SetHandled` stops the search. `RequestExceptionActionProcessorStrategy` defaults to `ApplyForUnhandledExceptions` (actions see only exceptions no handler handled); `ApplyForAllExceptions` runs them for every exception. Both behaviours sit outside your own behaviours, and in 14.2 they are added only if the scan found an implementation when `AddMediatR` ran.

code

csharp · 9 lines
csharp
public sealed class RenewLeaseFailureAction(ILogger<RenewLeaseFailureAction> logger)
    : IRequestExceptionAction<RenewLease, Exception>
{
    public Task Execute(RenewLease request, Exception exception, CancellationToken cancellationToken)
    {
        logger.LogWarning(exception, "Lease {LeaseId} renewal failed", request.LeaseId);
        return Task.CompletedTask;
    }
}

go deeper

for a junior

Recall the split: an exception handler can replace the exception with a response, an exception action can only observe it before it is rethrown.

for a middle

Explain how MediatR picks handlers from the most specific exception type upwards, stops at SetHandled, and runs all matching actions.

for a senior

Reason about placement: both behaviours wrap your own behaviours, the default strategy hides handled exceptions from actions, and a missing scan means the behaviour is never added.

for a principal

Decide which failures are business outcomes translated inside the command pipeline and which belong to the web edge, so exceptions are not hidden from monitoring.

## Two interfaces, two powers MediatR offers two exception hooks for requests, both in the `MediatR.Pipeline` namespace and both found by the `AddMediatR` assembly scan: | | `IRequestExceptionHandler<TRequest, TResponse, TException>` | `IRequestExceptionAction<TRequest, TException>` | |---|---|---| | Method | `Task Handle(TRequest, TException, RequestExceptionHandlerState<TResponse>, CancellationToken)` | `Task Execute(TRequest, TException, CancellationToken)` | | Can change the outcome | yes, `state.SetHandled(response)` | no | | How many run | until one calls `SetHandled` | every matching action | | After it runs | response returned, or exception rethrown | exception always rethrown | | Typical use | turn a known failure into a valid response | log, count, alert | Each is executed by a MediatR behaviour: `RequestExceptionProcessorBehavior` for handlers and `RequestExceptionActionProcessorBehavior` for actions. Each wraps the rest of the pipeline in a `try/catch`. ## How a handler is chosen When the inner pipeline throws, the handler behaviour: 1. walks the exception's type hierarchy from the thrown type up to `Exception` (for `LeaseNotFoundException : Exception`, that is two levels); 2. for each level resolves every `IRequestExceptionHandler<TRequest, TResponse, ThatType>`, drops a handler whose class is a base class of another handler's class, and orders the rest so that those in the request's assembly, then its namespace, come first; 3. removes duplicates of the same handler class; 4. invokes them in that order, stopping at the first that calls `SetHandled`. If none handles it, the original exception is rethrown with its stack trace. One more detail: `SetHandled(null)` for a reference-type `TResponse` is treated as not handled, and the exception is rethrown. Actions are gathered the same way, but all of them run, and then the exception is rethrown. ## Handlers versus actions: the strategy `MediatRServiceConfiguration.RequestExceptionActionProcessorStrategy` decides how the two behaviours nest: - **`ApplyForUnhandledExceptions`** (default): the action behaviour is registered first, so it is outside the handler behaviour. An exception a handler handled never reaches the actions; they see only failures that will reach the caller. - **`ApplyForAllExceptions`**: the order flips, so actions run for every exception, including those a handler then turns into a response. ## Where they sit and when they exist - `AddMediatR` registers both exception behaviours **before** your `cfg.AddBehavior` / `AddOpenBehavior` list, so they wrap your behaviours: a `ValidationException` thrown by a validation behaviour reaches matching exception handlers and actions. - They are registered **only if implementations exist** in the service collection when `AddMediatR` runs, which scanned classes do. An exception handler you register yourself after `AddMediatR`, in an app that has no other, is in the container but nothing ever calls it. - Closed implementations are registered for the interfaces they implement; open-generic implementations (`class Audit<TRequest, TException> : IRequestExceptionAction<TRequest, TException>`) are registered as open generics. ## In the property-management API ```csharp public sealed class LeaseNotFoundHandler : IRequestExceptionHandler<RenewLease, LeaseRenewal, LeaseNotFoundException> { public Task Handle(RenewLease request, LeaseNotFoundException exception, RequestExceptionHandlerState<LeaseRenewal> state, CancellationToken cancellationToken) { state.SetHandled(LeaseRenewal.NotFound(request.LeaseId)); return Task.CompletedTask; } } ``` `RenewLease` now returns a `NotFound` renewal instead of throwing, for every caller: the API endpoint and the job that renews leases at month end. ## Common mistakes - **Writing one handler per subtype.** A handler for `IRequestExceptionHandler<RenewLease, LeaseRenewal, Exception>` covers every exception type, because MediatR walks the hierarchy up to `Exception`; there is no need for one handler per exception subtype. - **Handling too broadly.** A handler for `Exception` that always calls `SetHandled` converts database outages into ordinary-looking responses. - **Logging twice.** An exception action that logs, plus the web edge that logs the same rethrown exception, doubles every error entry. - **Forgetting the strategy.** Under the default, a metric counted in an action misses every failure a handler recovered from. ## When to use them at all In an ASP.NET Core API, the usual home for turning exceptions into responses is the web edge (`IExceptionHandler`, ProblemDetails), because the result there is an HTTP status. MediatR's hooks earn their place when the translation is a **business** decision that must hold for non-HTTP callers too, or for actions such as per-command failure metrics. Converting every exception into a response inside MediatR hides failures from the edge, so keep handlers narrow and specific.

  • With MediatR's default strategy, a handler handles LeaseNotFoundException. Does an IRequestExceptionAction<RenewLease, Exception> run?
    No. Under `ApplyForUnhandledExceptions` the action behaviour wraps the handler behaviour, so once a handler calls `SetHandled` the response flows back out and no exception reaches the actions. Set `RequestExceptionActionProcessorStrategy.ApplyForAllExceptions` to flip the nesting and run actions for every exception.
  • You register an IRequestExceptionHandler with services.AddTransient after AddMediatR, and it never runs. Why?
    In 14.2 `AddMediatR` adds `RequestExceptionProcessorBehavior` only if it finds an `IRequestExceptionHandler` implementation already in the service collection; when none was scanned, the behaviour that would call yours is never registered. Put the handler in a scanned assembly or register it before `AddMediatR`.

  • An IRequestExceptionAction can swallow the exception and return a response.
  • MediatR tries base-type Exception handlers before the specific exception's handlers.
  • By default, exception actions also run for exceptions a handler handled.
  • Every matching exception handler runs even after one calls SetHandled.
  • Exception handlers only see exceptions thrown by the request handler, not by behaviours.

Assumes MediatR 14.2: exception handlers and actions are scanned by AddMediatR, RequestExceptionActionProcessorStrategy defaults to ApplyForUnhandledExceptions, and the two behaviours are registered only when implementations exist at AddMediatR time.