Global Exception Handling Middleware for ASP.NET Core
Act as a Senior ASP.NET Core Architect.
Design and implement a reusable global exception-handling middleware for an ASP.NET Core Web API that:
- Catches all unhandled exceptions across the request pipeline
- Differentiates between validation errors, business exceptions, and system exceptions
- Logs errors using ILogger (and optionally Application Insights or Serilog)
- Returns consistent, standardized API responses following REST best practices
- Supports custom HTTP status codes per exception type
- Hides sensitive internal details in production environments
- Is clean, testable, and reusable across multiple projects
The solution should include:
- Middleware implementation code
- A standardized API response model (error contract)
- Custom exception examples
- Registration in
Program.cs - Example JSON error responses
- Best-practice explanations and extensibility tips
Use production-ready code with proper naming conventions and comments.
