Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python -- Send Email When Exception Is Raised?

Tags:

I have a python class with many methods():

Method1()

Method2()

...........

...........

MethodN()

All methods -- while performing different tasks -- have the same scheme:

do something do something else has anything gone wrong?     raise an exception 

I want to be able to get an email whenever an exception is raised anywhere in the class.

Is there some easy way to combine this logic into the class, rather than calling SendEmail() before every raise Exception statement? what is the right, pythonic way to deal with such a case? canh a 'generalized' Exception handler be the solution? I'd be glad for any ideas you may have.

like image 264
user3262424 Avatar asked May 31 '11 03:05

user3262424


People also ask

Can Python send an email with attachment?

Use Python's built-in smtplib library to send basic emails. Send emails with HTML content and attachments using the email package. Send multiple personalized emails using a CSV file with contact data.

How do you send an exception in Python?

As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.


1 Answers

like @User said before Python has logging.handlers.SMTPHandler to send logged error message. Use logging module! Overriding exception class to send an email is a bad idea.

Quick example:

import logging import logging.handlers  smtp_handler = logging.handlers.SMTPHandler(mailhost=("smtp.example.com", 25),                                             fromaddr="[email protected]",                                              toaddrs="[email protected]",                                             subject=u"AppName error!")   logger = logging.getLogger() logger.addHandler(smtp_handler)  try:   break except Exception as e:   logger.exception('Unhandled Exception') 
like image 138
Darek Avatar answered Oct 21 '22 14:10

Darek