Overview
The exception handling system provides:- Custom Exception Types: Specific exceptions for common error scenarios
- Global Exception Handler: Centralized exception handling using ASP.NET Core’s
IExceptionHandler - Problem Details: Standardized error responses following RFC 7807
- Automatic Status Codes: Maps exceptions to appropriate HTTP status codes
Custom Exception Types
BadRequestException
Used when the request is invalid or contains bad data.BuildingBlocks/Exceptions/BadRequestException.cs
NotFoundException
Used when a requested resource cannot be found.BuildingBlocks/Exceptions/NotFoundException.cs
InternalServerException
Used for internal server errors and unexpected exceptions.BuildingBlocks/Exceptions/InternalServerException.cs
Global Exception Handler
TheCustomExceptionHandler implements IExceptionHandler to catch and handle all exceptions globally.
BuildingBlocks/Exceptions/Handler/CustomExceptionHandler.cs
Key Features
- Automatic Mapping: Maps exception types to HTTP status codes
- Structured Logging: Logs all exceptions with timestamp
- Problem Details: Returns RFC 7807 compliant error responses
- Trace ID: Includes correlation ID for tracking
- Validation Errors: Includes detailed validation errors for
ValidationException
Exception to Status Code Mapping
| Exception Type | HTTP Status Code | Status |
|---|---|---|
BadRequestException | 400 | Bad Request |
ValidationException | 400 | Bad Request |
NotFoundException | 404 | Not Found |
InternalServerException | 500 | Internal Server Error |
| Other exceptions | 500 | Internal Server Error |
Registration
Register the exception handler in your Program.cs:Validation Exception Response
When FluentValidation throws aValidationException, the handler includes detailed validation errors:
Request:
Best Practices
Use Appropriate Exception Types
Use Appropriate Exception Types
Choose the exception type that best represents the error condition.
Provide Clear Error Messages
Provide Clear Error Messages
Error messages should be clear and actionable for API consumers.
Don't Expose Internal Details
Don't Expose Internal Details
Avoid exposing sensitive information or internal implementation details in error messages.
Let ValidationBehavior Handle Validation
Let ValidationBehavior Handle Validation
Use FluentValidation validators instead of throwing exceptions manually for validation.
Error Response Example
Here’s a complete example of how exceptions flow through the system:Related Topics
Validation Behavior
Learn how validation exceptions are thrown
CQRS Pattern
See how to throw exceptions in handlers
