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.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 14 views 0 copies

Python code

24 lines
Python 3.9+
EXCEPTION_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

stdout
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

  1. Use `dict.get(exception_type, 500)` for a one-liner lookup without explicit try/except.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.