David Y.
—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 HTTPException
s, 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?
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")
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.