Best Practice Exception Handling in ASP.NET
Core Web API
Introduction
In modern microservices and RESTful API architectures, how
you handle errors is just as important as how you handle success. A naive
approach to exception handling—such as wrapping every controller action in a
try-catch block or leaking raw stack traces to the client—introduces security
risks, degrades maintainability, and ruins developer experience for consumers
of your API.
The goal is to implement a centralized, extensible,
performant, and standardized exception handling system that:
1.
Adheres to the RFC 7807 Problem Details
standard.
2.
Uses the native ASP.NET Core
IExceptionHandler (introduced in .NET 8).
3.
Leverages custom domain exceptions mapped to
appropriate HTTP status codes.
4.
Ensures structured logging and zero sensitive
information leaks.
1. Core Concepts & Architectural Strategy
Before looking at code, let's understand the core pillars
of an enterprise-grade exception handling framework:
Key Principles:
- Centralization:
No repeated try-catch blocks inside controllers or application logic. Use
middleware/handlers to catch uncaught exceptions at the framework level.
- Standardization
(RFC 7807): Return error responses as standard
ProblemDetails JSON objects. This ensures clients (Angular, React, Mobile
apps, or third-party integrators) always receive a predictable payload.
- Separation
of Concerns: Distinguish between Expected
Domain/Validation Errors (4xx status codes like 400 Bad Request, 404
Not Found) and Unexpected System Errors (5xx status codes like 500
Internal Server Error).
- Security
& Clean Logging: Stack traces, internal SQL errors,
and server details must only go into secure log sinks (e.g., Serilog,
Application Insights), never to the API client response.
2. Standard HTTP Error Code Mapping
· Mapping domain exceptions to proper HTTP status codes keeps your RESTful
API clean and predictable:
|
HTTP Status Code |
Meaning |
When to Use |
|
400 Bad Request |
Validation / Client Syntax Error |
Input fails validation rules or payload structure is invalid. |
|
401 Unauthorized |
Authentication Failure |
Missing or invalid JWT token/API key. |
|
403 Forbidden |
Authorization Failure |
Authenticated user lacks permission for the resource. |
|
404 Not Found |
Resource Missing |
Requested Entity ID does not exist in the database. |
|
409 Conflict |
Business State Rule Violation |
Attempting to register an email that already exists. |
|
422 Unprocessable Entity |
Semantic Validation |
Complex business logic validation failure. |
|
500 Internal Server Error |
Unexpected Exception |
NullReferenceException, Database Timeout, Unhandled system bugs. |
0 Comments
If you have any queries, please let me know. Thanks.