Home > Net >  Slack Notification for Python try, except method
Slack Notification for Python try, except method

Time:01-23

I am trying to write a python code with the try and except method where anytime an exception occurs it should give me a slack notification with the exception occurred. Here is the code that I have written:

try:
    with MailBox('imap.gmail.com').login(username, password) as mailbox:
         print(mailbox)                                      
except Exception as e:
    print(e)
    slack_message = {'text': e}

    http = urllib3.PoolManager()
    response = http.request('POST',
                            slack_webhook_url,
                            body=json.dumps(slack_message),
                            headers={'Content-Type': 'application/json'},
                            retries=False)

but it gave me the following error:

TypeError: Object of type MailboxLoginError is not JSON serializable

From Error, I understand that the body needs to be JSON serializable but not sure how to solve it. Can you help me? Thank you

CodePudding user response:

When you try to dump an Exception it fails because it's a Python object and you should transform it to a string like in the code below:

try:
    with MailBox('imap.gmail.com').login(username, password) as mailbox:
         print(mailbox)                                      
except Exception as e:
    print(e)
    slack_message = {'text': str(e)}  # Change type of "e" to string

    http = urllib3.PoolManager()
    response = http.request('POST',
                            slack_webhook_url,
                            body=json.dumps(slack_message),
                            headers={'Content-Type': 'application/json'},
                            retries=False)
  • Related