Skip to content

Commit 6aa7c00

Browse files
committed
possible solution to fix 1153 added
1 parent a6db70c commit 6aa7c00

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

aws_lambda_powertools/event_handler/api_gateway.py

+11-1
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,17 @@ def _lookup_exception_handler(self, exp_type: Type) -> Optional[Callable]:
651651
def _call_exception_handler(self, exp: Exception, route: Route) -> Optional[ResponseBuilder]:
652652
handler = self._lookup_exception_handler(type(exp))
653653
if handler:
654-
return ResponseBuilder(handler(exp), route)
654+
try:
655+
return ResponseBuilder(handler(exp), route)
656+
except ServiceError as ex:
657+
return ResponseBuilder(
658+
Response(
659+
status_code=ex.status_code,
660+
content_type=content_types.APPLICATION_JSON,
661+
body=self._json_dump({"statusCode": ex.status_code, "message": ex.msg}),
662+
),
663+
route,
664+
)
655665

656666
if isinstance(exp, ServiceError):
657667
return ResponseBuilder(

tests/functional/event_handler/test_api_gateway.py

+24
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from typing import Dict
1010

1111
import pytest
12+
from botocore.exceptions import ClientError
1213

1314
from aws_lambda_powertools.event_handler import content_types
1415
from aws_lambda_powertools.event_handler.api_gateway import (
@@ -1177,6 +1178,29 @@ def get_lambda() -> Response:
11771178
assert result["body"] == "CUSTOM ERROR FORMAT"
11781179

11791180

1181+
def test_exception_handler_botocore_client_error(json_dump):
1182+
# GIVEN
1183+
app = ApiGatewayResolver()
1184+
1185+
@app.exception_handler(ClientError)
1186+
def client_error(ex: ClientError):
1187+
raise BadRequestError("Bad request")
1188+
1189+
@app.get("/my/path")
1190+
def get_lambda() -> Response:
1191+
raise ClientError(error_response={}, operation_name="op-name")
1192+
1193+
# WHEN calling the event handler
1194+
# AND a ClientError is raised
1195+
result = app(LOAD_GW_EVENT, {})
1196+
1197+
# THEN call the exception_handler
1198+
assert result["statusCode"] == 400
1199+
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
1200+
expected = {"statusCode": 400, "message": "Bad request"}
1201+
assert result["body"] == json_dump(expected)
1202+
1203+
11801204
def test_exception_handler_not_found():
11811205
# GIVEN a resolver with an exception handler defined for a 404 not found
11821206
app = ApiGatewayResolver()

0 commit comments

Comments
 (0)