|
| 1 | +from typing import Dict, cast |
| 2 | + |
| 3 | +import starlette.exceptions as exceptions |
| 4 | +import starlette.responses as responses |
| 5 | +from starlette.types import ASGIApp, Receive, Scope, Send |
| 6 | + |
| 7 | + |
| 8 | +class ErrorMiddleware: |
| 9 | + """Inserts shiny-autoreload.js into the head. |
| 10 | +
|
| 11 | + It's necessary to do it using middleware instead of in a nice htmldependency, |
| 12 | + because we want autoreload to be effective even when displaying an error page. |
| 13 | + """ |
| 14 | + |
| 15 | + def __init__(self, app: ASGIApp): |
| 16 | + self.app = app |
| 17 | + |
| 18 | + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: |
| 19 | + try: |
| 20 | + return await self.app(scope, receive, send) |
| 21 | + except exceptions.HTTPException as e: |
| 22 | + resp = responses.PlainTextResponse( |
| 23 | + e.detail, |
| 24 | + e.status_code, |
| 25 | + headers=cast( |
| 26 | + Dict[str, str], |
| 27 | + e.headers, # pyright: ignore[reportUnknownMemberType] |
| 28 | + ), |
| 29 | + media_type="text/plain", |
| 30 | + ) |
| 31 | + await resp(scope, receive, send) |
| 32 | + except Exception as e: |
| 33 | + # Seems super weird this is just going to stdout, should we use logger or |
| 34 | + # at least stderr? |
| 35 | + print("Unhandled error: " + str(e)) |
| 36 | + resp = responses.PlainTextResponse( |
| 37 | + "An internal server error occurred", 500, media_type="text/plain" |
| 38 | + ) |
| 39 | + await resp(scope, receive, send) |
0 commit comments