From 260d36d8ac564cfac5b699683b15e4f6e55ec98e Mon Sep 17 00:00:00 2001 From: Michael Brewer Date: Tue, 26 Apr 2022 10:51:30 -0700 Subject: [PATCH] fix(event_handler): handle exception_handler riasing ServiceError Changes: - Allow for exception_handler raising a ServicerError - Add test case with this scenario --- .../event_handler/api_gateway.py | 5 +++- .../event_handler/test_api_gateway.py | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/aws_lambda_powertools/event_handler/api_gateway.py b/aws_lambda_powertools/event_handler/api_gateway.py index 5d57c645b2..f4731dd4ec 100644 --- a/aws_lambda_powertools/event_handler/api_gateway.py +++ b/aws_lambda_powertools/event_handler/api_gateway.py @@ -651,7 +651,10 @@ def _lookup_exception_handler(self, exp_type: Type) -> Optional[Callable]: def _call_exception_handler(self, exp: Exception, route: Route) -> Optional[ResponseBuilder]: handler = self._lookup_exception_handler(type(exp)) if handler: - return ResponseBuilder(handler(exp), route) + try: + return ResponseBuilder(handler(exp), route) + except ServiceError as service_error: + exp = service_error if isinstance(exp, ServiceError): return ResponseBuilder( diff --git a/tests/functional/event_handler/test_api_gateway.py b/tests/functional/event_handler/test_api_gateway.py index 9b5835c8b2..c0bce92d92 100644 --- a/tests/functional/event_handler/test_api_gateway.py +++ b/tests/functional/event_handler/test_api_gateway.py @@ -1210,3 +1210,27 @@ def handle_not_found(_) -> Response: # THEN call the @app.not_found() function assert result["statusCode"] == 404 + + +def test_exception_handler_raises_service_error(json_dump): + # SCENARIO: Support an exception_handler that raises a ServiceError + # GIVEN + app = ApiGatewayResolver() + + @app.exception_handler(ValueError) + def client_error(ex: ValueError): + raise BadRequestError("Bad request") + + @app.get("/my/path") + def get_lambda() -> Response: + raise ValueError("foo") + + # WHEN calling the event handler + # AND a ValueError is raised + result = app(LOAD_GW_EVENT, {}) + + # THEN call the exception_handler + assert result["statusCode"] == 400 + assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON + expected = {"statusCode": 400, "message": "Bad request"} + assert result["body"] == json_dump(expected)