Skip to content

Commit c67efe4

Browse files
Michael Brewerheitorlessa
Michael Brewer
andauthored
fix(event_handler): exception_handler to handle ServiceError exceptions (#1160)
Co-authored-by: Heitor Lessa <[email protected]>
1 parent c92bde6 commit c67efe4

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

Diff for: aws_lambda_powertools/event_handler/api_gateway.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -656,7 +656,10 @@ def _lookup_exception_handler(self, exp_type: Type) -> Optional[Callable]:
656656
def _call_exception_handler(self, exp: Exception, route: Route) -> Optional[ResponseBuilder]:
657657
handler = self._lookup_exception_handler(type(exp))
658658
if handler:
659-
return ResponseBuilder(handler(exp), route)
659+
try:
660+
return ResponseBuilder(handler(exp), route)
661+
except ServiceError as service_error:
662+
exp = service_error
660663

661664
if isinstance(exp, ServiceError):
662665
return ResponseBuilder(

Diff for: tests/functional/event_handler/test_api_gateway.py

+23
Original file line numberDiff line numberDiff line change
@@ -1217,6 +1217,29 @@ def handle_not_found(_) -> Response:
12171217
assert result["statusCode"] == 404
12181218

12191219

1220+
def test_exception_handler_raises_service_error(json_dump):
1221+
# GIVEN an exception handler raises a ServiceError (BadRequestError)
1222+
app = ApiGatewayResolver()
1223+
1224+
@app.exception_handler(ValueError)
1225+
def client_error(ex: ValueError):
1226+
raise BadRequestError("Bad request")
1227+
1228+
@app.get("/my/path")
1229+
def get_lambda() -> Response:
1230+
raise ValueError("foo")
1231+
1232+
# WHEN calling the event handler
1233+
# AND a ValueError is raised
1234+
result = app(LOAD_GW_EVENT, {})
1235+
1236+
# THEN call the exception_handler
1237+
assert result["statusCode"] == 400
1238+
assert result["headers"]["Content-Type"] == content_types.APPLICATION_JSON
1239+
expected = {"statusCode": 400, "message": "Bad request"}
1240+
assert result["body"] == json_dump(expected)
1241+
1242+
12201243
def test_event_source_compatibility():
12211244
# GIVEN
12221245
app = APIGatewayHttpResolver()

0 commit comments

Comments
 (0)