Skip to main content

Exception Hierarchy

Key points:
  • HTTPException is a subclass of StarletteHTTPException.
  • RequestValidationError is not an HTTPException.
  • All of them ultimately inherit from Python’s Exception.

Three Types of Exceptions

1. HTTP Exceptions

HTTP exceptions represent expected errors that are intentionally raised by your application or internally by FastAPI/Starlette. Example:
Register the handler using:

Why StarletteHTTPException?

The hierarchy is
Using StarletteHTTPException allows a single handler to catch:
  • HTTP exceptions raised by your application.
  • HTTP exceptions raised internally by FastAPI/Starlette (404 Route Not Found, 405 Method Not Allowed, etc.).

2. Request Validation Exceptions

Before executing a route, FastAPI validates the incoming request using Pydantic. Example:
Request
Since "abc" cannot be converted into an integer, FastAPI raises a RequestValidationError. The route function is never executed. Register the handler using:
Although it is not an HTTPException, FastAPI automatically converts it into a 422 Unprocessable Content response.

3. Programming Exceptions

Programming exceptions are unexpected runtime errors caused by bugs. Examples:
  • ZeroDivisionError
  • AttributeError
  • TypeError
  • ValueError
Example:
Register the global handler using:
Since almost every Python runtime exception inherits from Exception, this acts as a fallback handler and usually returns a 500 Internal Server Error.

Which Handler is Called?

HTTP Exception

Invalid Request

Programming Error

FastAPI always chooses the most specific matching handler.

Request Flow

Rule of Thumb

  • Use raise HTTPException() when you intentionally want to return an HTTP error.
  • Handle StarletteHTTPException to customize all HTTP errors, including those raised by your application and by FastAPI/Starlette.
  • Handle RequestValidationError to customize request validation errors returned by Pydantic.
  • Handle Exception as the global fallback for unexpected programming errors.
Define all handlers in a single file.
Register them once when creating the application.
Every router automatically uses these handlers.
If an exception occurs inside any router, FastAPI searches the application’s registered handlers and executes the most specific matching one. Therefore, exception handlers are application-level components, not router-level components.