Option 1
You could add custom exception handlers, and use attributes in your Exception
class (i.e., MyException(Exception)
in the example below), in order to pass a custom message or variables. The exception handler (in the example below, that is, my_exception_handler()
with the @app.exception_handler(MyException)
decorator) will handle the exception as you wish and return your custom message. For more options, please have a look at this related answer as well.
Working Example
In order to trigger the exception in the example below, call the /items/{item_id}
endpoint using an item_id
that is not present in the items
dictionary.
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
class MyException(Exception):
def __init__(self, item_id: str):
self.item_id = item_id
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.exception_handler(MyException)
async def my_exception_handler(request: Request, exc: MyException):
return JSONResponse(status_code=status.HTTP_404_NOT_FOUND,
content={"message": f"Item for '{exc.item_id}' cannot be found." })
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise MyException(item_id=item_id)
return {"item": items[item_id]}
In case you wouldn't like using the @app.exception_handler()
decorator, you could remove the decorator from the my_exception_handler()
funciton and instead use the add_exception_handler()
method to add the handler to the app
instance. Example:
app.add_exception_handler(MyException, my_exception_handler)
Another way to add the exception handler to the app
instance would be to use the exception_handlers
parameter of the FastAPI class, as demonstrated in this answer. Related answers can also be found here and here.
Option 2
You could always use HTTPException
to return HTTP responses with custom errors to the client (as well as add custom headers to the HTTP error).
Working Example
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}