Skip to content

Static typing: allow to pass dict as argument to exception classes #7279

@laurens-teirlynck

Description

@laurens-teirlynck

Static type checker used

mypy (project's standard)

AWS Lambda function runtime

3.13

Powertools for AWS Lambda (Python) version

latest

Static type checker info

When trying to call this endpoint, a application/json response is returned, but the typing in the exception classes from event_handler/exceptions.py only allow str.

http -v :3000/hello/bob
GET /hello/bob HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:3000
User-Agent: HTTPie/3.2.4


HTTP/1.1 404 NOT FOUND
Connection: close
Content-Length: 82
Content-Type: application/json
Date: Fri, 29 Aug 2025 09:31:53 GMT
Server: Werkzeug/3.1.3 Python/3.13.7

{
    "message": {
        "msg": "no person named bob",
        "type": "name.not_found"
    },
    "statusCode": 404
}

Code snippet

from aws_lambda_powertools.event_handler import APIGatewayRestResolver
from aws_lambda_powertools.event_handler.exceptions import NotFoundError

app = APIGatewayRestResolver()


@app.get("/hello/<name>")
def hello_name(name: str):
    raise NotFoundError(
        {
            "type": "name.not_found",
            "msg": f"no person named {name}",
        }
    )


def lambda_handler(event, context):
    return app.resolve(event, context)

Possible Solution

A simple fix would be to change

class ServiceError(Exception):
    """Powertools class HTTP Service Error"""

    def __init__(self, status_code: int, msg: str):

with

class ServiceError(Exception):
    """Powertools class HTTP Service Error"""

    def __init__(self, status_code: int, msg: str | dict):

But I'm not familiar enough with the codebase to know if this can cause other issues.

Metadata

Metadata

Labels

good first issueGood for newcomerstypingStatic typing definition related issues (mypy, pyright, etc.)

Projects

Status

Coming soon

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions