Showing posts with label exception. Show all posts
Showing posts with label exception. Show all posts

Aug 6, 2012

How to log an exception instance

http://blog.tplus1.com/index.php/2012/08/05/python-log-uncaught-exceptions-with-sys-excepthook/

If you do any of these, you probably won’t like what you get:
logging.error(ex)
logging.error(str(ex))
In both cases, you are just turning the exception to a string. You won’t see the traceback and you won’t see the exception type.
Instead of those, make sure you do one of these:
logging.exception(ex) # this is exactly what logging.exception does inside
logging.error(ex, exc_info=1) # sets a higher log level than error 
logging.critical(ex, exc_info=1)
For the last two, without that exc_info=1 parameter, you won’t see the traceback in your logs. You’ll just see the message from the exception.

Aug 3, 2012

Attaching custom exceptions to functions and classes

http://pydanny.com/attaching-custom-exceptions-to-functions-and-classes.html

class DoesNotCompute(Exception):
    """ Easy to understand naming conventions work best! """
    pass

def this_function(x):
    """ This function only works on numbers."""
    try:
        return x ** x
    except TypeError:
        raise DoesNotCompute

# Assign DoesNotCompute exception to this_function
this_function.DoesNotCompute = DoesNotCompute
>>> try:
...     this_function('is an example')
... except this_function.DoesNotCompute:
...     print('See what attaching custom exceptions to functions can do?')
...
...
See what attaching custom exceptions to functions can do?