Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Slack Notification for Python try, except method

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use