Handling errs

Notes Single

Exception throw

from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"foo": "The Foo Wrestlers"}

async def read_item_header(item_id: str):
    if item_id not in items:
        raise HTTPException(
            detail="Item not found",
            headers={"X-Error": "There goes my error"},
    return {"item": items[item_id]}

Error handler

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

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

app = FastAPI()

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

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

Thanks for reading :)
I invite you to continue reading other entries and visiting us again soon.

Related Posts: