Your Ad could be here. I want to connect my readers to relavant ads. If you have a product targeted at developers, let's talk. [email protected]

Here's my thought on Handling Errors - FastAPI

This page shows how to customize your fastapi errors. I found this very useful to setup common templates so that I can return the same 404's both programatically and by default, so it all looks the same to the end user.

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

class UnicornException(Exception):
    def __init__(self, name: str): = name

app = FastAPI()

async def unicorn_exception_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        content={"message": f"Oops! {} did something. There goes a rainbow..."},

async def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"unicorn_name": name}

This post was a thought by Waylon Walker see all my thoughts at