Custom exception handling in FastAPI

David Y.
jump to solution

The Problem

I’m reworking a FastAPI project to use several custom exceptions rather than FastAPI’s default HTTPException. I’ve defined the exception classes and handler functions. Here’s an example:

from fastapi import FastAPI, HTTPException, status
from fastapi.responses import JSONResponse
from fastapi import Request

app = FastAPI()

class MyException(HTTPException):
    pass

@app.exception_handler(MyException)
def my_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND, content={"message": "404 file not found"})

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

When I was using HTTPExceptions, I could pass a message to the exception, for example:

raise HTTPException(status_code=404, detail="Item not found")

Is there a way to pass a message to custom exceptions?

The Solution

An exception handler function takes two arguments: the request and the exception. The exception is an instance of the custom exception class. Like any custom class, we can define and assign attributes for our exceptions and access them in the exception handler. For example:

class MyException(HTTPException):
    def __init__(self, message: str):  # define and assign a message attribute
        self.message = message

@app.exception_handler(MyException)
def my_exception_handler(request: Request, exc: HTTPException):
    return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,
                        content={"message": exc.message})  # use the exc object's message attribute

Then we can provide an arbitrary message when we raise the exception, as was previously done with HTTPException:

raise MyException(message="Can't find the item")

Production Error Handling

While custom exception handlers help you return clean API responses during development, python error handling in production requires visibility into when and why exceptions occur. Production environments surface error patterns you won’t catch locally—specific user inputs that trigger validation errors, edge cases in business logic, or exceptions that only happen under concurrent load. Error monitoring tools automatically capture your custom exceptions with full context including request parameters, user information, and the execution path, helping you identify patterns and fix the root causes rather than just handling symptoms.

Considered "not bad" by 4 million developers and more than 150,000 organizations worldwide, Sentry provides code-level observability to many of the world's best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Sentry