10
10
from typing import Dict
11
11
12
12
import pytest
13
+ from pydantic import BaseModel
13
14
14
15
from aws_lambda_powertools .event_handler import content_types
15
16
from aws_lambda_powertools .event_handler .api_gateway import (
@@ -1465,7 +1466,6 @@ def test_exception_handler_with_data_validation():
1465
1466
1466
1467
@app .exception_handler (RequestValidationError )
1467
1468
def handle_validation_error (ex : RequestValidationError ):
1468
- print (f"request path is '{ app .current_event .path } '" )
1469
1469
return Response (
1470
1470
status_code = 422 ,
1471
1471
content_type = content_types .TEXT_PLAIN ,
@@ -1486,6 +1486,34 @@ def get_lambda(param: int):
1486
1486
assert result ["body" ] == "Invalid data. Number of errors: 1"
1487
1487
1488
1488
1489
+ def test_exception_handler_with_data_validation_pydantic_response ():
1490
+ # GIVEN a resolver with an exception handler defined for RequestValidationError
1491
+ app = ApiGatewayResolver (enable_validation = True )
1492
+
1493
+ class Err (BaseModel ):
1494
+ msg : str
1495
+
1496
+ @app .exception_handler (RequestValidationError )
1497
+ def handle_validation_error (ex : RequestValidationError ):
1498
+ return Response (
1499
+ status_code = 422 ,
1500
+ content_type = content_types .APPLICATION_JSON ,
1501
+ body = Err (msg = f"Invalid data. Number of errors: { len (ex .errors ())} " ),
1502
+ )
1503
+
1504
+ @app .get ("/my/path" )
1505
+ def get_lambda (param : int ):
1506
+ ...
1507
+
1508
+ # WHEN calling the event handler
1509
+ # AND a RequestValidationError is raised
1510
+ result = app (LOAD_GW_EVENT , {})
1511
+
1512
+ # THEN exception handler's pydantic response should be serialized correctly
1513
+ assert result ["statusCode" ] == 422
1514
+ assert result ["body" ] == '{"msg":"Invalid data. Number of errors: 1"}'
1515
+
1516
+
1489
1517
def test_data_validation_error ():
1490
1518
# GIVEN a resolver without an exception handler
1491
1519
app = ApiGatewayResolver (enable_validation = True )
0 commit comments