Sentry Answers>FastAPI>

Custom exception handling in FastAPI

Custom exception handling in FastAPI

David Y.

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:

Click to Copy
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:

Click to Copy
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:

Click to Copy
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:

Click to Copy
raise MyException(message="Can't find the item")
  • Syntax.fmListen to the Syntax Podcast
  • Community SeriesIdentify, Trace, and Fix Endpoint Regression Issues
  • ResourcesBackend Error Monitoring 101
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,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.

© 2024 • Sentry is a registered Trademark of Functional Software, Inc.