| 1 |
from fastapi import FastAPI, Request |
| 2 |
from fastapi.responses import JSONResponse |
| 3 |
|
| 4 |
|
| 5 |
class UnicornException(Exception): |
| 6 |
def __init__(self, name: str): |
| 7 |
self.name = name |
| 8 |
|
| 9 |
|
| 10 |
app = FastAPI() |
| 11 |
|
| 12 |
|
| 13 |
@app.exception_handler(UnicornException) |
| 14 |
async def unicorn_exception_handler(request: Request, exc: UnicornException): |
| 15 |
return JSONResponse( |
| 16 |
status_code=418, |
| 17 |
content={"message": f"Oops! {exc.name} did something. There goes a rainbow..."}, |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
@app.get("/unicorns/{name}") |
| 22 |
async def read_unicorn(name: str): |
| 23 |
if name == "yolo": |
| 24 |
raise UnicornException(name=name) |
| 25 |
return {"unicorn_name": name} |