Skip to content

Feature request: app.exception_handler does not work when used in separate file #1193

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

Closed
heitorlessa opened this issue Apr 29, 2022 Discussed in #1191 · 11 comments · Fixed by #3979
Closed

Feature request: app.exception_handler does not work when used in separate file #1193

heitorlessa opened this issue Apr 29, 2022 Discussed in #1191 · 11 comments · Fixed by #3979
Assignees
Labels

Comments

@heitorlessa
Copy link
Contributor

Discussed in #1191

Originally posted by arunbhati April 29, 2022
Hi,

I am using APIGatewayRestResolver and I'm having trouble working with @app.exception_handler. When I have APIGatewayRestResolver object and @app.exception_handler decorator in same file then it works but if I create a separate file for exceptions(exceptions.py) and do the import of APIGatewayRestResolver then it doesn't work.
Following are steps to reproduce.

  1. Create a lambda function in Python with Lambda Layer for AWS Powertools from here.
  2. Attach this Zip file to lambda function - Zip file: Archive.zip
  3. Use following input for Lambda request
{
  "resource": "/proxy",
  "path": "/proxy",
  "httpMethod": "GET",
  "headers": null
}
  1. Lambda function should fail with following error
{
  "errorMessage": "",
  "errorType": "ValueError",
  "requestId": "24f06853-16fc-4657-9360-40409f0726be",
  "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 10, in lambda_handler\n    return axis_controllers.main(event, context)\n",
    "  File \"/var/task/src/abc/axis_controllers.py\", line 11, in main\n    return app.resolve(event, context)\n",
    "  File \"/opt/python/aws_lambda_powertools/event_handler/api_gateway.py\", line 498, in resolve\n    return self._resolve().build(self.current_event, self._cors)\n",
  1. Now move ValueError exception method from exceptions.py into init.py file in same folder.
  2. Rerun test with same input and now lambda output will show expected result(shown below).
{
  "statusCode": 400,
  "headers": {
    "Content-Type": "text/plain"
  },
  "body": "Invalid request",
  "isBase64Encoded": false
}

I don't have much expertise on how decorator works so any help here would be appreciated.
Thanks.

@heitorlessa heitorlessa added bug Something isn't working triage Pending triage from maintainers and removed bug Something isn't working triage Pending triage from maintainers labels Apr 29, 2022
@heitorlessa
Copy link
Contributor Author

hey @arunbhati thanks for sending over an archive to help reproduce it quickly! The issue is that exceptions.py code is never executed, because it isn't being imported anywhere else.

To confirm it, I've added a dummy constant within exceptions.py and imported it from your lambda_function.py. I'm gonna close this and create a feature request to support defining exception handlers within in separate files via Router instances - this will make the process more easily in the future (after our pause).

lambda_function.py

import src.abc.axis_controllers as axis_controllers
from src.abc.exceptions import HELLO   # HERE!

def lambda_handler(event, context):

    return axis_controllers.main(event, context)



event = {
  "resource": "/proxy",
  "path": "/proxy",
  "httpMethod": "GET",
  "headers": ""
}

print(HELLO)
lambda_handler(event, {})

exceptions.py

from aws_lambda_powertools.event_handler import content_types
from aws_lambda_powertools.event_handler.api_gateway import Response
from aws_lambda_powertools.event_handler.exceptions import NotFoundError

from src.abc import app

HELLO = "WORLD"

@app.exception_handler(ValueError)
def handle_value_error(ex: ValueError):
    metadata = {"path": app.current_event.path}
    print(f"Malformed request: {metadata}")

    return Response(
        status_code=400,
        content_type=content_types.TEXT_PLAIN,
        body="Invalid request",
    )


@app.not_found
def handle_not_found_errors(exc: NotFoundError) -> Response:
    # Return 418 upon 404 errors
    print(f"Not found route: {app.current_event.path}")
    return Response(
        status_code=418,
        content_type=content_types.TEXT_PLAIN,
        body="I'm a teapot!"
    )

@jasmarc
Copy link

jasmarc commented Feb 9, 2023

I'm gonna close this and create a feature request to support defining exception handlers within in separate files via Router instances - this will make the process more easily in the future (after our pause).

Hi @heitorlessa did you actually create this feature request? I'm having trouble finding it. Was it every implemented, if so?

@heitorlessa
Copy link
Contributor Author

@SzymonSwic
Copy link

SzymonSwic commented Sep 21, 2023

Hi @heitorlessa, has this issue been solved with the mentioned PR: #1824? With newest version of powertools (2.25.0) I am not able to define exception handlers in a separate file with Router. Is there some other way to achieve it?

@rajalokan
Copy link

rajalokan commented Sep 25, 2023

Agree to SzymonSwic. I can confirm separate routes using (router) works. However, I'm still unsure how to split the exceptions to a separate file. The Router class doesn't seem to have interface to register exception.

I'm happy to contribute if I am assisted a little bit. Thanks!!

@heitorlessa
Copy link
Contributor Author

oh hey, seeing this only now as it was closed -- That's something else, that would be a feature request to add exception_handler to the Router class. It was an oversight. This issue was for App not Router.

@rajalokan if you've got the bandwidth, it'll need two changes (we need a feature request issue):

@alecrevangelista
Copy link

Any update on this feature @heitorlessa // @rajalokan ?

@leandrodamascena
Copy link
Contributor

Reopening this issue as using @router.exception_handler still doesn't work.

Sending a PR in few minutes.

@leandrodamascena
Copy link
Contributor

Thank you for commenting here and bringing this issue to our attention @alecrevangelista!

@leandrodamascena leandrodamascena self-assigned this Mar 18, 2024
@leandrodamascena leandrodamascena changed the title app.exception_handler does not work when used in separate file Feature request: app.exception_handler does not work when used in separate file Mar 18, 2024
Copy link
Contributor

⚠️COMMENT VISIBILITY WARNING⚠️

This issue is now closed. Please be mindful that future comments are hard for our team to see.

If you need more assistance, please either tag a team member or open a new issue that references this one.

If you wish to keep having a conversation with other community members under this issue feel free to do so.

@github-actions github-actions bot added the pending-release Fix or implementation already in dev waiting to be released label Mar 19, 2024
Copy link
Contributor

This is now released under 2.36.0 version!

@github-actions github-actions bot removed the pending-release Fix or implementation already in dev waiting to be released label Mar 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
6 participants