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

feat(apigateway): add exception_handler support #898

Merged
merged 6 commits into from
Dec 16, 2021

Conversation

michaelbrewer
Copy link
Contributor

@michaelbrewer michaelbrewer commented Dec 15, 2021

Issue #, if available:

Description of changes:

app = ApiGatewayResolver()


@app.exception_handler(SomeKindOfError)
def handle_error(ex: SomeKindOfError):
   print(f"request path is '{app.current_event.path}'")
   return Response(
       status_code=418,
       content_type=content_types.TEXT_HTML,
       body=str(ex),
   )


@app.not_found()
def handle_not_found(exc: NotFoundError):
    return Response(status_code=404, content_type=content_types.TEXT_PLAIN, body="I am a teapot!")


@app.exception_handler(ServiceError)
def service_error(ex: ServiceError):
    logger.debug(f"Log out sensitive stuff: {ex.msg}")
    return Response(
        status_code=ex.status_code,
        content_type=content_types.APPLICATION_JSON,
        body="CUSTOM ERROR FORMAT",
    )


@app.get("/my/path")
def call_with_error() -> Response:
   raise SomeKindOfError("Foo!")

Checklist

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@pull-request-size pull-request-size bot added the size/M Denotes a PR that changes 30-99 lines, ignoring generated files. label Dec 15, 2021
@codecov-commenter
Copy link

codecov-commenter commented Dec 15, 2021

Codecov Report

Merging #898 (eb1d7a8) into develop (e91932c) will increase coverage by 0.00%.
The diff coverage is 100.00%.

Impacted file tree graph

@@           Coverage Diff            @@
##           develop     #898   +/-   ##
========================================
  Coverage    99.88%   99.88%           
========================================
  Files          118      118           
  Lines         5139     5162   +23     
  Branches       573      578    +5     
========================================
+ Hits          5133     5156   +23     
  Misses           2        2           
  Partials         4        4           
Impacted Files Coverage Δ
aws_lambda_powertools/event_handler/api_gateway.py 100.00% <100.00%> (ø)

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e91932c...eb1d7a8. Read the comment docs.

@michaelbrewer michaelbrewer changed the title feat(event-handler): Add exception_handler support (RFC) feat(event-handler): Add exception_handler support to api gw (see RFC) Dec 15, 2021
@pull-request-size pull-request-size bot added size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/M Denotes a PR that changes 30-99 lines, ignoring generated files. labels Dec 15, 2021
Copy link
Contributor

@heitorlessa heitorlessa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's looking great, thank you for implementing it that quick.

One major question to better understand the int as GitHub Mobile isn't showing me all the code easily.

aws_lambda_powertools/event_handler/api_gateway.py Outdated Show resolved Hide resolved
aws_lambda_powertools/event_handler/api_gateway.py Outdated Show resolved Hide resolved
Copy link
Contributor

@heitorlessa heitorlessa left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor ask on testing subclass exceptions. If you can't I can do it tomorrow, as I'll merge this along with others in prep for the release.

@heitorlessa
Copy link
Contributor

heitorlessa commented Dec 16, 2021 via email

@michaelbrewer
Copy link
Contributor Author

@heitorlessa - it would have to be a different implementation

    def _lookup_exception_handler(self, exp_type: Type) -> Optional[Callable]:
        for cls in exp_type.__mro__:
            if cls in self._exception_handlers:
                return self._exception_handlers[cls]
        return None

vs

    def _lookup_exception_handler(self, exp_type: Type) -> Optional[Callable]:
        for cls in self._exception_handlers.keys()
            if issubclass(exp_type, cls):
                return self._exception_handlers[cls]
        return None

Also we will be aware that order should either matter OR not:

app = ApiGatewayResolver()


@app.exception_handler(InternalServiceError)
def internal_service_error(ex: InternalServiceError):
    ...


@app.exception_handler(ServiceError)
def generic_service_error(ex: ServiceError):
    ...

@heitorlessa
Copy link
Contributor

I see it now, this would likely happen and order is important (MRO is better).

I'll merge as is and write the docs tomorrow

@heitorlessa heitorlessa changed the title feat(event-handler): Add exception_handler support to api gw (see RFC) feat(apigateway): add exception_handler support Dec 16, 2021
@heitorlessa heitorlessa added the feature New feature or functionality label Dec 16, 2021
@heitorlessa heitorlessa merged commit 8c859de into aws-powertools:develop Dec 16, 2021
@michaelbrewer michaelbrewer deleted the feat-exception-handler branch December 16, 2021 19:33
@michaelbrewer
Copy link
Contributor Author

I see it now, this would likely happen and order is important (MRO is better).

I'll merge as is and write the docs tomorrow

We could possibly expand on the tests to be sure we have a contract of that the behavior would be.

heitorlessa added a commit to heitorlessa/aws-lambda-powertools-python that referenced this pull request Dec 17, 2021
…tools-python into feat/batch-new-processor

* 'develop' of https://github.com/awslabs/aws-lambda-powertools-python:
  fix(parser): kinesis sequence number is str, not int (aws-powertools#907)
  feat(apigateway): add exception_handler support (aws-powertools#898)
  fix(event-sources): Pass authorizer data to APIGatewayEventAuthorizer (aws-powertools#897)
  chore(deps): bump fastjsonschema from 2.15.1 to 2.15.2 (aws-powertools#891)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or functionality size/L Denotes a PR that changes 100-499 lines, ignoring generated files. tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants