#! /usr/bin/env python3 ''' sns_error_notification is intended as a wrapper around the `lambda_handler()` function in an AWS serverless design. It catches errors and exceptions and posts them to an sns queue, which can then be subscribed to for emails or handled by another lambda function. To use: 1) Set the environment variable 'sns_error_topic' in your lambda function to the arn of an SNS topic. 2) Ensure your lambda function has permission for `sns:Publish` to the sns topic. 3) Import this function via `from sns_error_notification import sns_error_nofication` 4) Add `@sns_error_notification` directly before your lambda_handler definition (`def lambda_handler(event, context):`) WARNING: Could potentially generate a lot of email traffic on a high volume function. Watch your execution errors metric in CloudWatch before deploying. See https://github.com/fdamstra/sns_error_notification ''' import boto3 import json import os import traceback def sns_error_notification(function_name): def wrapper(event, context): if os.environ.get('sns_notifications_enabled', 'true') == 'false': return function_name(event, context) try: sns_arn = os.environ.get('sns_error_topic', 'Please set an environment variable "sns_error" topic') snsclient = boto3.client('sns') function_name(event, context) except Exception as e: # First level error handling, send full details subject = f'Execution Error in {context.function_name}' estr = str(e) tb = traceback.format_exc() try: event_dump = json.dumps(event, indent=2) except: event_dump = "ERROR" try: context_dump = vars(context) except: context_dump = "ERROR" message = (f'Exception:\n{estr}\n\n' f'Traceback:\n{tb}\n\n' f'Event:\n{event_dump}\n\n' f'Context:\n{context_dump}\n' ) # Only happens if there was an exception snsclient.publish( TopicArn=sns_arn, Subject=subject, Message=message ) raise return wrapper