Error Code Reference
400 Bad Request
Returned when the request contains invalid data or an operation cannot be performed.General bad request error. The request was malformed or contains invalid parameters.Triggered by:
ArgumentException in middleware or explicit controller returnsMessage: Varies based on the specific validation failureOne or more model validation errors occurred. Check the
errors field for field-specific validation messages.Triggered by: ASP.NET Core model validation (DataAnnotations)Default message: “Uno o más campos tienen errores de validación.”Common causes:- Missing required fields
- Invalid data format (e.g., email, date)
- Data constraints violated (e.g., string too long, number out of range)
Program.cs:28-43 via InvalidModelStateResponseFactoryThe requested operation is not allowed in the current state or context.Triggered by:
InvalidOperationException thrown in business logicMessage: Exception message from the thrown InvalidOperationExceptionExample scenarios:- Attempting to delete a resource that has dependencies
- Performing an action on a resource in the wrong state
- Business rule violation (e.g., “Usuario no está registrado como residente.”)
ExceptionHandlingMiddleware.cs:43401 Unauthorized
Returned when authentication is required but not provided or is invalid.Authentication required or authentication credentials are invalid.Triggered by:
UnauthorizedAccessExceptionin middleware- Explicit
Unauthorized()returns in controllers - JWT authentication failure
- Missing
Authorizationheader - Expired JWT token
- Invalid JWT token signature
- Invalid username or password (login endpoint)
ExceptionHandlingMiddleware.cs:46403 Forbidden
Returned when the authenticated user does not have permission to access the resource.Current status: The API uses
Forbid() in some controllers but does not return a structured ApiErrorResponse for 403 errors.Controllers return ASP.NET Core’s default 403 response without the standard error format.Common scenarios:- Resident attempting to access another resident’s data
- User without admin role attempting admin operations
404 Not Found
Returned when the requested resource does not exist.The requested resource could not be found.Triggered by:
KeyNotFoundExceptionin middleware- Explicit
NotFound()orNotFoundApiError()in controllers
- Invalid resource ID
- Resource was deleted
- Incorrect endpoint URL
- Exception handled in
ExceptionHandlingMiddleware.cs:45 - Extension method in
ControllerBaseExtensions.cs:27
409 Conflict
Returned when the request conflicts with the current state of the server.Current status: The API has a
ConflictApiError() extension method available but is not actively used in the current codebase.Typical use cases:- Duplicate resource creation (e.g., username already exists)
- Optimistic concurrency conflicts
- Resource state conflicts
ControllerBaseExtensions.cs:40500 Internal Server Error
Returned when an unexpected error occurs on the server.An unexpected internal server error occurred.Triggered by: Any unhandled exception that doesn’t match other specific exception typesProduction message: “Ha ocurrido un error interno. Intente más tarde.”Development message: Full exception message for debuggingImplementation: Default case in
ExceptionHandlingMiddleware.cs:52-56A database operation failed unexpectedly.Triggered by:
DbUpdateException from Entity Framework CoreProduction message: “Error al guardar los datos. Intente de nuevo.”Development message: Inner exception message or main exception messageCommon causes:- Database constraint violations
- Connection failures
- Transaction timeouts
traceId if the error persists.Implementation: Exception handled in ExceptionHandlingMiddleware.cs:47-51HTTP Status Code Summary
| HTTP Status | Error Codes | Usage |
|---|---|---|
| 400 | BAD_REQUEST, INVALID_OPERATION, VALIDATION_ERROR | Invalid data or operation not permitted |
| 401 | UNAUTHORIZED | Not authenticated (missing or invalid token) |
| 403 | (no structured error) | Authenticated but lacking permission |
| 404 | NOT_FOUND | Resource not found |
| 409 | (extension available but unused) | Conflict (e.g., duplicate resource) |
| 500 | INTERNAL_ERROR, DATABASE_ERROR | Internal server error |
Source Code Reference
Exception Handling Middleware
File:HappyHabitat.API/Middleware/ExceptionHandlingMiddleware.cs
Key logic: Lines 36-70
Model Validation Configuration
File:HappyHabitat.API/Program.cs
Key logic: Lines 25-44
Controller Extension Methods
File:HappyHabitat.API/Extensions/ControllerBaseExtensions.cs
Available methods:
Common Error Scenarios
Scenario 1: Validation Failure
Request:POST /api/pets
400 Bad Request
Scenario 2: Resource Not Found
Request:GET /api/pets/99999
Response: 404 Not Found
Scenario 3: Invalid Credentials
Request:POST /api/auth/login
401 Unauthorized
ApiErrorResponse format.
Scenario 4: Expired Token
Request:GET /api/residents/me (with expired JWT)
Response: 401 Unauthorized
Scenario 5: Invalid Operation
Request:POST /api/comentarios
Response: 400 Bad Request
Scenario 6: Database Error
Request:POST /api/communities (with constraint violation)
Response: 500 Internal Server Error
Production:
Error Handling Best Practices
Use Error Codes
Rely on the
code field for programmatic decision-making, not the message field which may change or be in different languages.Display Messages
Show the
message field to users as it’s designed to be human-readable. Note that messages are in Spanish.Handle Field Errors
When
errors is present (validation failures), display field-specific messages in your forms for better UX.Include Trace IDs
Always include the
traceId when reporting issues to support for faster resolution. It correlates with server logs.