mirror of
https://github.com/fastapi/fastapi.git
synced 2025-12-28 00:30:58 -05:00
Co-authored-by: Yurii Motov <yurii.motov.monte@gmail.com> Co-authored-by: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com>
26 lines
626 B
Python
26 lines
626 B
Python
from fastapi import FastAPI, Request
|
|
from fastapi.responses import JSONResponse
|
|
|
|
|
|
class UnicornException(Exception):
|
|
def __init__(self, name: str):
|
|
self.name = name
|
|
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
@app.exception_handler(UnicornException)
|
|
async def unicorn_exception_handler(request: Request, exc: UnicornException):
|
|
return JSONResponse(
|
|
status_code=418,
|
|
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."},
|
|
)
|
|
|
|
|
|
@app.get("/unicorns/{name}")
|
|
async def read_unicorn(name: str):
|
|
if name == "yolo":
|
|
raise UnicornException(name=name)
|
|
return {"unicorn_name": name}
|