Custom exception handling in FastAPI
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")
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.