| 1 |
from litestar import Litestar, Request, Response, get |
| 2 |
from litestar.exceptions import HTTPException, ValidationException |
| 3 |
from litestar.params import FromQuery |
| 4 |
|
| 5 |
|
| 6 |
def app_exception_handler(request: Request, exc: HTTPException) -> Response: |
| 7 |
return Response( |
| 8 |
content={ |
| 9 |
"error": "server error", |
| 10 |
"path": request.url.path, |
| 11 |
"detail": exc.detail, |
| 12 |
"status_code": exc.status_code, |
| 13 |
}, |
| 14 |
status_code=500, |
| 15 |
) |
| 16 |
|
| 17 |
|
| 18 |
def router_handler_exception_handler(request: Request, exc: ValidationException) -> Response: |
| 19 |
return Response( |
| 20 |
content={"error": "validation error", "path": request.url.path}, |
| 21 |
status_code=400, |
| 22 |
) |
| 23 |
|
| 24 |
|
| 25 |
@get("/") |
| 26 |
async def index() -> None: |
| 27 |
raise HTTPException("something's gone wrong") |
| 28 |
|
| 29 |
|
| 30 |
@get( |
| 31 |
"/greet", |
| 32 |
exception_handlers={ValidationException: router_handler_exception_handler}, |
| 33 |
) |
| 34 |
async def greet(name: FromQuery[str]) -> str: |
| 35 |
return f"hello {name}" |
| 36 |
|
| 37 |
|
| 38 |
app = Litestar( |
| 39 |
route_handlers=[index, greet], |
| 40 |
exception_handlers={HTTPException: app_exception_handler}, |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
# run: / |
| 45 |
# run: /greet |