Skip to content

Commit 88b2425

Browse files
authored
Exception handlers from settings (#182)
* Make exception handlers load from settings
1 parent a93f0e3 commit 88b2425

4 files changed

Lines changed: 32 additions & 22 deletions

File tree

docs/en/docs/release-notes.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ hide:
55

66
# Release Notes
77

8-
98
## 0.15.5
109

1110
### Added
1211

1312
- Support for multiplexing a session into multiple session contexts.
1413
- Added support for `redirect_exception` when using [WSGIMiddleware](./middleware.md#wsgimiddleware). This
1514
flag when passed, you can add a `HTTPException` exception handler that will make Lilya capture the WSGI exceptions.
15+
- Exception handlers on a global level can now be passed via [settings](./settings.md)
1616

1717
### Changed
1818

lilya/apps.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -939,7 +939,9 @@ async def populate_g(connection: Connection):
939939

940940
self.debug = self.load_settings_value("debug", debug, is_boolean=True)
941941

942-
self.exception_handlers = {} if exception_handlers is None else dict(exception_handlers)
942+
self.exception_handlers = (
943+
self.load_settings_value("exception_handlers", exception_handlers) or {}
944+
)
943945
self.custom_middleware = [
944946
wrap_middleware(middleware)
945947
for middleware in self.load_settings_value("middleware", middleware) or []

tests/encoders/settings.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,35 @@
11
from dataclasses import dataclass
2+
from json import loads
3+
from typing import Any
24

5+
from pydantic import ValidationError
6+
7+
from lilya import status
8+
from lilya.requests import Request
9+
from lilya.responses import JSONResponse
10+
from lilya.types import ExceptionHandler
311
from tests.settings import TestSettings
412

513

14+
async def validation_error_exception_handler(
15+
request: Request, exc: ValidationError
16+
) -> JSONResponse: # pragma: no cover
17+
"""
18+
This handler is to be used when a pydantic validation error is triggered during the logic
19+
of a code block and not the definition of a handler.
20+
21+
This is different from validation_error_exception_handler
22+
"""
23+
status_code = status.HTTP_422_UNPROCESSABLE_ENTITY
24+
return JSONResponse({"detail": loads(exc.json())}, status_code=status_code)
25+
26+
627
@dataclass
728
class EncoderSettings(TestSettings):
829
infer_body: bool = True
30+
31+
@property
32+
def exception_handlers(self) -> ExceptionHandler | dict[Any, Any]:
33+
return {
34+
ValidationError: validation_error_exception_handler,
35+
}

tests/encoders/test_infer_body_simple_validation.py

Lines changed: 1 addition & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,10 @@
1-
from json import loads
1+
from pydantic import BaseModel
22

3-
from pydantic import BaseModel, ValidationError
4-
5-
from lilya import status
6-
from lilya.requests import Request
7-
from lilya.responses import JSONResponse
83
from lilya.routing import Path
94
from lilya.testclient import create_client
105
from tests.encoders.settings import EncoderSettings
116

127

13-
async def validation_error_exception_handler(
14-
request: Request, exc: ValidationError
15-
) -> JSONResponse: # pragma: no cover
16-
"""
17-
This handler is to be used when a pydantic validation error is triggered during the logic
18-
of a code block and not the definition of a handler.
19-
20-
This is different from validation_error_exception_handler
21-
"""
22-
status_code = status.HTTP_422_UNPROCESSABLE_ENTITY
23-
return JSONResponse({"detail": loads(exc.json())}, status_code=status_code)
24-
25-
268
class User(BaseModel):
279
name: str
2810
age: int
@@ -36,7 +18,6 @@ def test_infer_body_error(test_client_factory):
3618
with create_client(
3719
routes=[Path("/infer", handler=process_body, methods=["POST"])],
3820
settings_module=EncoderSettings,
39-
exception_handlers={ValidationError: validation_error_exception_handler},
4021
) as client:
4122
response = client.post("/infer")
4223

0 commit comments

Comments
 (0)