lambda_function.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #! /usr/bin/env python3
  2. import boto3
  3. import json
  4. import traceback
  5. # Insert original code here:
  6. # Rename your original lambda_handler() to lambda_handler_noemail()
  7. def lambda_handler_noemail(event, context):
  8. # if you start generating too many emails, you can always change
  9. # the handler back to this.
  10. return True
  11. # Make this your caller.
  12. def lambda_handler(event, context):
  13. # Set this to an SNS topic you'd like to publish to.
  14. sns_arn = 'arn:aws:sns:us-east-2:1234567890:lambda-errors',
  15. try:
  16. snsclient = boto3.client('sns')
  17. return lambda_handler_unhandled(event, context)
  18. except Exception as e:
  19. subject = f'Execution Error in {context.function_name}'
  20. estr = str(e)
  21. tb = traceback.format_exc()
  22. try:
  23. event_dump = json.dumps(event, indent=2)
  24. except:
  25. event_dump = "ERROR"
  26. try:
  27. context_dump = vars(context)
  28. except:
  29. context_dump = "ERROR"
  30. message = f'Exception: {estr}\n\nTraceback: {tb}\n\nEvent: {event_dump}\n\nContext: {context_dump}\n'
  31. # Only happens if there was an exception
  32. snsclient.publish(
  33. Subject=subject,
  34. TopicArn=sns_arn,
  35. Message=message
  36. )
  37. raise