Debian Codegraph @

docs/examples/application_hooks/after_exception_hook.py

raw
1 import logging
2 from typing import TYPE_CHECKING
3
4 from litestar import Litestar, get
5 from litestar.exceptions import HTTPException
6 from litestar.status_codes import HTTP_400_BAD_REQUEST
7
8 logger = logging.getLogger()
9
10 if TYPE_CHECKING:
11 from litestar.types import Scope
12
13
14 @get("/some-path", sync_to_thread=False)
15 def my_handler() -> None:
16 """Route handler that raises an exception."""
17 raise HTTPException(detail="bad request", status_code=HTTP_400_BAD_REQUEST)
18
19
20 async def after_exception_handler(exc: Exception, scope: "Scope") -> None:
21 """Hook function that will be invoked after each exception."""
22 state = Litestar.from_scope(scope).state
23 if not hasattr(state, "error_count"):
24 state.error_count = 1
25 else:
26 state.error_count += 1
27
28 logger.info(
29 "an exception of type %s has occurred for requested path %s and the application error count is %d.",
30 type(exc).__name__,
31 scope["path"],
32 state.error_count,
33 )
34
35
36 app = Litestar([my_handler], after_exception=[after_exception_handler])