How to Build an Error Code Enum in Python
Define an API error code enum with descriptions and build structured error payloads for HTTP responses.
Python code
37 linesfrom enum import Enum
class APIErrorCode(Enum):
SUCCESS = 0
BAD_REQUEST = 400
UNAUTHORIZED = 401
FORBIDDEN = 403
NOT_FOUND = 404
CONFLICT = 409
INTERNAL_ERROR = 500
def describe_error(code):
descriptions = {
APIErrorCode.SUCCESS: "Request completed successfully",
APIErrorCode.BAD_REQUEST: "Malformed request or invalid parameters",
APIErrorCode.UNAUTHORIZED: "Missing or invalid authentication credentials",
APIErrorCode.FORBIDDEN: "Client lacks permission to access resource",
APIErrorCode.NOT_FOUND: "Requested resource does not exist",
APIErrorCode.CONFLICT: "Request conflicts with current system state",
APIErrorCode.INTERNAL_ERROR: "Unexpected server-side failure",
}
return descriptions.get(code, "Unknown error code")
def build_error_payload(code):
return {
"success": code == APIErrorCode.SUCCESS,
"code": code.value,
"name": code.name,
"message": describe_error(code),
}
if __name__ == "__main__":
for err in APIErrorCode:
print(build_error_payload(err))
Output
{'success': True, 'code': 0, 'name': 'SUCCESS', 'message': 'Request completed successfully'}
{'success': False, 'code': 400, 'name': 'BAD_REQUEST', 'message': 'Malformed request or invalid parameters'}
{'success': False, 'code': 401, 'name': 'UNAUTHORIZED', 'message': 'Missing or invalid authentication credentials'}
{'success': False, 'code': 403, 'name': 'FORBIDDEN', 'message': 'Client lacks permission to access resource'}
{'success': False, 'code': 404, 'name': 'NOT_FOUND', 'message': 'Requested resource does not exist'}
{'success': False, 'code': 409, 'name': 'CONFLICT', 'message': 'Request conflicts with current system state'}
{'success': False, 'code': 500, 'name': 'INTERNAL_ERROR', 'message': 'Unexpected server-side failure'}
How it works
The Enum class provides named constants with associated values (HTTP status codes). The describe_error function maps each enum member to a human-readable message using a dictionary, and build_error_payload returns a consistent dictionary structure for API responses. Iterating over APIErrorCode yields each member in definition order, and code.value accesses the underlying HTTP status code. This pattern keeps error handling centralized and type-safe.
Common mistakes
- Forgetting to call `.value` when you need the numeric code instead of the enum member.
- Using `Enum` instead of `IntEnum` if you need the numeric value to work as an integer in comparisons or serialization.
- Not including a default/fallback case in the description lookup, leading to KeyError.
Variations
- Use `class APIErrorCode(IntEnum)` to make the enum values directly usable as integers.
- Add a `description` attribute to each enum member by extending the class with a custom `__init__`.
Real-world use cases
- Returning structured error payloads from a REST API to keep responses consistent for client-side error handling.
- Mapping internal exceptions to standard HTTP status codes in a web framework like FastAPI or Django.
- Logging and monitoring error codes in a microservices environment to quickly identify failure patterns.
Sponsored
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.