Exception Hierarchy
HTTPExceptionis a subclass ofStarletteHTTPException.RequestValidationErroris not anHTTPException.- 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:Why StarletteHTTPException?
The hierarchy is
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:"abc" cannot be converted into an integer, FastAPI raises a RequestValidationError.
The route function is never executed.
Register the handler using:
HTTPException, FastAPI automatically converts it into a 422 Unprocessable Content response.
3. Programming Exceptions
Programming exceptions are unexpected runtime errors caused by bugs. Examples:ZeroDivisionErrorAttributeErrorTypeErrorValueError
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
Request Flow
Rule of Thumb
- Use
raise HTTPException()when you intentionally want to return an HTTP error. - Handle
StarletteHTTPExceptionto customize all HTTP errors, including those raised by your application and by FastAPI/Starlette. - Handle
RequestValidationErrorto customize request validation errors returned by Pydantic. - Handle
Exceptionas the global fallback for unexpected programming errors.