| 1 |
from litestar import Litestar, MediaType, Request, Response, get |
| 2 |
from litestar.exceptions import HTTPException |
| 3 |
from litestar.status_codes import HTTP_500_INTERNAL_SERVER_ERROR |
| 4 |
|
| 5 |
|
| 6 |
def plain_text_exception_handler(_: Request, exc: Exception) -> Response: |
| 7 |
"""Default handler for exceptions subclassed from HTTPException.""" |
| 8 |
status_code = getattr(exc, "status_code", HTTP_500_INTERNAL_SERVER_ERROR) |
| 9 |
detail = getattr(exc, "detail", "") |
| 10 |
|
| 11 |
return Response( |
| 12 |
media_type=MediaType.TEXT, |
| 13 |
content=detail, |
| 14 |
status_code=status_code, |
| 15 |
) |
| 16 |
|
| 17 |
|
| 18 |
@get("/") |
| 19 |
async def index() -> None: |
| 20 |
raise HTTPException(detail="an error occurred", status_code=400) |
| 21 |
|
| 22 |
|
| 23 |
app = Litestar( |
| 24 |
route_handlers=[index], |
| 25 |
exception_handlers={HTTPException: plain_text_exception_handler}, |
| 26 |
) |
| 27 |
|
| 28 |
# run: / |