1010from typing import Dict
1111
1212import pytest
13+ from pydantic import BaseModel
1314
1415from aws_lambda_powertools .event_handler import content_types
1516from aws_lambda_powertools .event_handler .api_gateway import (
@@ -1465,7 +1466,6 @@ def test_exception_handler_with_data_validation():
14651466
14661467 @app .exception_handler (RequestValidationError )
14671468 def handle_validation_error (ex : RequestValidationError ):
1468- print (f"request path is '{ app .current_event .path } '" )
14691469 return Response (
14701470 status_code = 422 ,
14711471 content_type = content_types .TEXT_PLAIN ,
@@ -1486,6 +1486,34 @@ def get_lambda(param: int):
14861486 assert result ["body" ] == "Invalid data. Number of errors: 1"
14871487
14881488
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+
14891517def test_data_validation_error ():
14901518 # GIVEN a resolver without an exception handler
14911519 app = ApiGatewayResolver (enable_validation = True )
0 commit comments