Skip to content

feat(apigateway): add exception_handler support #898

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

Merged
merged 6 commits into from
Dec 16, 2021
Merged
Changes from 1 commit
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
Prev Previous commit
Next Next commit
feat: allow for overriding ServiceErrors
  • Loading branch information
Michael Brewer committed Dec 15, 2021
commit 5337dc35fa155cf07e6d1b9798eedfaa8f692636
33 changes: 18 additions & 15 deletions aws_lambda_powertools/event_handler/api_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,19 +610,10 @@ def _call_route(self, route: Route, args: Dict[str, str]) -> ResponseBuilder:
"""Actually call the matching route with any provided keyword arguments."""
try:
return ResponseBuilder(self._to_response(route.func(**args)), route)
except ServiceError as e:
return ResponseBuilder(
Response(
status_code=e.status_code,
content_type=content_types.APPLICATION_JSON,
body=self._json_dump({"statusCode": e.status_code, "message": e.msg}),
),
route,
)
except Exception as exc:
handler = self._lookup_exception_handler(exc)
if handler:
return ResponseBuilder(handler(exc))
response = self._call_exception_handler(exc, route)
if response:
return response

if self._debug:
# If the user has turned on debug mode,
Expand Down Expand Up @@ -687,10 +678,22 @@ def register_exception_handler(func: Callable):

return register_exception_handler

def _lookup_exception_handler(self, exc: Exception) -> Optional[Callable]:
for cls in type(exc).__mro__:
def _call_exception_handler(self, exp: Exception, route: Route) -> Optional[ResponseBuilder]:
for cls in type(exp).__mro__:
if cls in self._exception_handlers:
return self._exception_handlers[cls]
handler = self._exception_handlers[cls]
return ResponseBuilder(handler(exp), route)

if isinstance(exp, ServiceError):
return ResponseBuilder(
Response(
status_code=exp.status_code,
content_type=content_types.APPLICATION_JSON,
body=self._json_dump({"statusCode": exp.status_code, "message": exp.msg}),
),
route,
)

return None


Expand Down