Back to results for “Exception Handling”
.NET › Global Exception Handling & Middleware

How does exception handling middleware interact with model validation errors in ASP.NET Core, and how do they typically produce different error response paths?

Advanced

Answer

Model validation errors (from [ApiController]'s automatic model state validation, or FluentValidation-style validators) typically don't throw exceptions at all -- instead, [ApiController] automatically short-circuits with a 400 Bad Request and a ValidationProblemDetails response before the action method even executes, entirely bypassing exception-handling middleware since no exception was ever thrown; this is a distinct, separate error path from actual unhandled exceptions, which is why validation errors and unhandled exceptions often need separate consideration when designing a consistent overall error response strategy.
[ApiController]  // enables automatic model validation short-circuiting
public class ProductsController : ControllerBase {
    [HttpPost]
    public IActionResult Create([Required] ProductDto dto) {
        // If dto fails validation, this method body never executes --
        // [ApiController] already returned a 400 ValidationProblemDetails automatically
        return Ok();
    }
}
Real-world example A team designing their unified error response format realizes validation errors (automatic 400 responses) and unhandled exceptions (caught by exception middleware) are two entirely separate code paths that both need to produce a consistent ProblemDetails shape, requiring explicit configuration of both.

Common follow-ups: How do you customize the automatic validation error response format via InvalidModelStateResponseFactory?;How would you unify both paths to guarantee identical response shapes?