Skip to content

Commit

Permalink
fix(event_handler): exception_handler to handle ServiceError exceptio…
Browse files Browse the repository at this point in the history
…ns (#1160)

Co-authored-by: Heitor Lessa <[email protected]>
  • Loading branch information
Michael Brewer and heitorlessa authored Apr 28, 2022
1 parent c92bde6 commit c67efe4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
5 changes: 4 additions & 1 deletion aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,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(
Expand Down
23 changes: 23 additions & 0 deletions tests/functional/event_handler/test_api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -1217,6 +1217,29 @@ def handle_not_found(_) -> Response:
assert result["statusCode"] == 404


def test_exception_handler_raises_service_error(json_dump):
# GIVEN an exception handler raises a ServiceError (BadRequestError)
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)


def test_event_source_compatibility():
# GIVEN
app = APIGatewayHttpResolver()
Expand Down

0 comments on commit c67efe4

Please sign in to comment.