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

AWS Lambda/APIGW unhandled exception causes UnboundLocalError #2399

Closed
alessandrobologna opened this issue Apr 9, 2024 · 0 comments · Fixed by #2418
Closed

AWS Lambda/APIGW unhandled exception causes UnboundLocalError #2399

alessandrobologna opened this issue Apr 9, 2024 · 0 comments · Fixed by #2418
Labels
bug Something isn't working

Comments

@alessandrobologna
Copy link
Contributor

alessandrobologna commented Apr 9, 2024

Describe your environment
AWS Lambda, python3.12, using opentelemetry-lambda layer-python 0.5 which includes opentelemetry-python 1.23.0 and opentelemetry-python-contrib 0.44b0

Steps to reproduce
A lambda function invoked with APIGW, with auto-instrumentation, after an unhandled exception causes:

[ERROR] UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
Traceback (most recent call last):
  File "/opt/python/wrapt/wrappers.py", line 598, in __call__
    return self._self_wrapper(self.__wrapped__, self._self_instance,
  File "/opt/python/opentelemetry/instrumentation/aws_lambda/__init__.py", line 378, in _instrumented_lambda_handler_call
    if isinstance(result, dict) and result.get("statusCode"):
    ^^^^^^

This can be reproduced with this code:

import json
import random
import logging

from opentelemetry import trace

tracer = trace.get_tracer_provider().get_tracer(__name__)
logger = logging.getLogger()


def lambda_handler(event, context):
    if random.random() < 0.1:  # 10% chance to raise an error
        raise Exception('Injected error')
    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": "hello world",
        }),
    }

What is the expected behavior?
The original exception is propagated (and not the UnboundLocalError)

What is the actual behavior?
The original exception is not propagated but this exception is raised instead:

[ERROR] UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
Traceback (most recent call last):
  File "/opt/python/wrapt/wrappers.py", line 598, in __call__
    return self._self_wrapper(self.__wrapped__, self._self_instance,
  File "/opt/python/opentelemetry/instrumentation/aws_lambda/__init__.py", line 378, in _instrumented_lambda_handler_call
    if isinstance(result, dict) and result.get("statusCode"):
    ^^^^^^

Additional context
It seems that it would be enough to declare result at the beginning of this block of code:

    result = None  # Assign a default value to result
    exception = None
            try:
                result = call_wrapped(*args, **kwargs)
            except Exception as exc:  # pylint: disable=W0703
                exception = exc
                span.set_status(Status(StatusCode.ERROR))
                span.record_exception(exception)

            if isinstance(lambda_event, dict) and lambda_event.get(
                "requestContext"
            ):
                span.set_attribute(SpanAttributes.FAAS_TRIGGER, "http")

                if lambda_event.get("version") == "2.0":
                    _set_api_gateway_v2_proxy_attributes(lambda_event, span)
                else:
                    _set_api_gateway_v1_proxy_attributes(lambda_event, span)

                if isinstance(result, dict) and result.get("statusCode"):
                    span.set_attribute(
                        SpanAttributes.HTTP_STATUS_CODE,
                        result.get("statusCode"),
                    )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant