Map Exception Type to HTTP Status Code in Python
Maps Python exception types to appropriate HTTP status codes using a dictionary lookup for consistent API error handling.
Python code
24 linesEXCEPTION_STATUS_MAP = {
ValueError: 400,
KeyError: 400,
TypeError: 400,
PermissionError: 403,
FileNotFoundError: 404,
AttributeError: 404,
TimeoutError: 408,
NotImplementedError: 501,
ConnectionError: 503,
}
def status_code_for(exception_type):
try:
return EXCEPTION_STATUS_MAP[exception_type]
except KeyError:
return 500
if __name__ == "__main__":
exception_types = [ValueError, KeyError, PermissionError, FileNotFoundError, TimeoutError, LookupError]
for exc_type in exception_types:
print(f"{exc_type.__name__}: {status_code_for(exc_type)}")
Output
ValueError: 400
KeyError: 400
PermissionError: 403
FileNotFoundError: 404
TimeoutError: 408
LookupError: 500
How it works
This pattern centralizes error-to-status-code mapping in a single dictionary, making it easy to maintain and extend. The status_code_for function first attempts a direct dictionary lookup and falls back to 500 (Internal Server Error) for unmapped exceptions, catching KeyError under the hood. Using exception types as dictionary keys is safe because they are hashable and unique. This approach avoids repetitive if/elif chains and keeps mapping logic declarative and readable.
Common mistakes
- Forgetting that some exceptions are subclasses — e.g., `KeyError` is a subclass of `LookupError` but not `ValueError`, so exact type matching matters.
- Assuming every unmapped exception should return 400 instead of a generic 500.
- Using exception instances instead of exception classes as dictionary keys, which won't match when catching types.
Variations
- Use `dict.get(exception_type, 500)` for a one-liner lookup without explicit try/except.
- Define a custom exception hierarchy with each class holding its own status code attribute.
Real-world use cases
- Centralizing error response codes in a FastAPI or Flask exception handler before returning JSON responses.
- Standardizing error codes across microservices for consistent client-side handling and monitoring.
- Building an API gateway that translates downstream service exceptions into meaningful HTTP status codes.
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.