Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(event_handler): exception_handler to handle ServiceError exceptions #1160

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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