Skip to content

Commit

Permalink
move fallback handler to wrapper.py
Browse files Browse the repository at this point in the history
  • Loading branch information
TalUsvyatsky committed Apr 23, 2024
1 parent 23e2cfc commit 85d0d7d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 24 deletions.
26 changes: 2 additions & 24 deletions datadog_lambda/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,36 +9,14 @@
import os
import time

from datadog_lambda.tracing import emit_telemetry_on_exception_outside_of_handler
from datadog_lambda.wrapper import datadog_lambda_wrapper
from datadog_lambda.wrapper import datadog_lambda_wrapper, error_fallback_handler
from datadog_lambda.module_name import modify_module_name


class HandlerError(Exception):
pass


class _ErrorFallbackHandler(object):
"""
Decorator for when an exception occurs outside of the handler function.
Emits telemetry and re-raises the exception.
"""

def __init__(self, exception, modified_mod_name, start_time_ns):
self.exception = exception
self.modified_mod_name = modified_mod_name
self.start_time_ns = start_time_ns

def __call__(self, event, context, **kwargs):
emit_telemetry_on_exception_outside_of_handler(
context,
self.exception,
self.modified_mod_name,
self.start_time_ns,
)
raise self.exception


path = os.environ.get("DD_LAMBDA_HANDLER", None)
if path is None:
raise HandlerError(
Expand All @@ -58,4 +36,4 @@ def __call__(self, event, context, **kwargs):
handler_func = getattr(handler_module, handler_name)
handler = datadog_lambda_wrapper(handler_func)
except Exception as e:
handler = _ErrorFallbackHandler(e, modified_mod_name, start_time_ns)
handler = error_fallback_handler(e, modified_mod_name, start_time_ns)
23 changes: 23 additions & 0 deletions datadog_lambda/wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
is_authorizer_response,
tracer,
propagator,
emit_telemetry_on_exception_outside_of_handler,
)
from datadog_lambda.trigger import (
extract_trigger_tags,
Expand Down Expand Up @@ -382,9 +383,31 @@ def _after(self, event, context):
logger.error(format_err_with_traceback(e))


class _ErrorFallbackHandler(object):
"""
Fallback handler for when an exception occurs outside of the handler function.
Emits telemetry and re-raises the exception.
"""

def __init__(self, exception, modified_mod_name, start_time_ns):
self.exception = exception
self.modified_mod_name = modified_mod_name
self.start_time_ns = start_time_ns

def __call__(self, event, context, **kwargs):
emit_telemetry_on_exception_outside_of_handler(
context,
self.exception,
self.modified_mod_name,
self.start_time_ns,
)
raise self.exception


def format_err_with_traceback(e):
tb = traceback.format_exc().replace("\n", "\r")
return f"Error {e}. Traceback: {tb}"


datadog_lambda_wrapper = _LambdaDecorator
error_fallback_handler = _ErrorFallbackHandler

0 comments on commit 85d0d7d

Please sign in to comment.