Simplified Exception Identification in Python
The name of the exception class is not enough to generalize properly the handling of exceptions. As an example, the socket module generates many different exceptions for various conditions, and they all are named "error". What makes each condition distinct lies in the exceptions details. The tuple ('error', (111, 'Connection refused') ) is different from ('error', (32, 'Broken pipe') ).
So what we will do instead is create a dictionary whose keys define exact exceptions. Each of those keys will have a simple integer value that reduces multiple cases to a smaller number. The following dictionary is not complete, but it gives a good idea of how to proceed and build a larger one.
EXC_DISCONNECT = 1
EXC_SERVER_NOT_AVAILABLE = 2
ExcDiagDict = {
# another famous OS:
repr( ('error', (10061, 'Connection refused') ) ) :
EXC_SERVER_NOT_AVAILABLE,
# Linux 2.4:
repr( ('error', (111, 'Connection refused') ) ) :
EXC_SERVER_NOT_AVAILABLE,
repr( ('error', (32, 'Broken pipe') ) ) : EXC_DISCONNECT,
repr( ('error', (107, 'Transport endpoint is not connected') ) ) :
EXC_DISCONNECT,
}
In this exception "diagnosis" dictionary, a repr() surrounds each of the tuples that makes up a key. In this example, strings are the only practical way to retrieve the expected results from the dictionary. Using a tuple directly does not work--no match would ever be found, unless the exact same instances of objects and tuples were used in the look-up. String keys are used because they are less restrictive and work according to their lexical values.
In the dictionary as it is initialized above, we have two keys associated with the constant EXC_SERVER_NOT_AVAILABLE. Each of these two keys represents an ('error', (number, 'Connection refused')) exception, but the value of the number varies according to the operating system being used. The last two keys are two completely different exceptions that can happen under Linux, but they basically indicate the same event--a disconnect on a socket. The dictionary can be expanded to include similar exception patterns on more platforms, as well as more exception patterns related to one or more basic events.
If you take the previous import statements, the previous definition of the function formatExceptionInfo() and the dictionary above, you can append the following code:
def getDiagnosisFromExcInfo(excInfoTuple):
try:
excPattern = (excInfoTuple[0], excInfoTuple[1])
return ExcDiagDict[ repr(excPattern) ]
except KeyError:
return None
except:
return None # maybe was not tuple?
from socket import *
try:
s = socket(AF_INET, SOCK_STREAM)
s.connect( ("127.0.0.1", 7788) )
s.close()
except:
exInfo = formatExceptionInfo()
diag = getDiagnosisFromExcInfo(exInfo)
print "diag:", diag, "exc:", exInfo
When you run that code, the following should be returned:
diag: 2 exc: ('error', (111, 'Connection refused'), ['File "<stdin>",
line 3, in ?\n', ...]
The "2" is the value of the constant EXC_SERVER_NOT_AVAILABLE, which is indeed the constant associated with the Connection refused exception pattern in the sample dictionary. From experience, it is safe to say that error recovery code that uses formatExceptionInfo() and getDiagnosisFromExcInfo() is much simpler and, therefore, more reliable.
With the function formatExceptionInfo(), we have found a way to learn important information about any exception from the Python sys.exc_info() function. Also, the exception patterns dictionary makes it possible to simplify the identification of various exceptions, even if they differ from one OS to another or if they actually refer to the same event.
Jean-Francois Touchette has been developing software for 20 years. He has written several gateways and servers with various protocols since 1985. He has been using C and UNIX since that time. When Python is suitable, he prefers it.
email: jftouchette@yahoo.com
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- New Products
- Linux Systems Administrator
- Senior Perl Developer
- Technical Support Rep
- UX Designer
- Web & UI Developer (JavaScript & j Query)
- Designing Electronics with Linux
- Dynamic DNS—an Object Lesson in Problem Solving
- Using Salt Stack and Vagrant for Drupal Development
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- another very interesting
1 hour 24 min ago - Reply to comment | Linux Journal
3 hours 17 min ago - Reply to comment | Linux Journal
10 hours 11 min ago - Reply to comment | Linux Journal
10 hours 28 min ago - Favorite (and easily brute-forced) pw's
12 hours 19 min ago - Have you tried Boxen? It's a
18 hours 11 min ago - seo services in india
22 hours 42 min ago - For KDE install kio-mtp
22 hours 43 min ago - Evernote is much more...
1 day 43 min ago - Reply to comment | Linux Journal
1 day 9 hours ago
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Featured Jobs
| Linux Systems Administrator | Houston and Austin, Texas | Host Gator |
| Senior Perl Developer | Austin, Texas | Host Gator |
| Technical Support Rep | Houston and Austin, Texas | Host Gator |
| UX Designer | Austin, Texas | Host Gator |
| Web & UI Developer (JavaScript & j Query) | Austin, Texas | Host Gator |
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?



Comments
Re: Simplified Exception Identification in Python
Dude, ever hear of errno?
errno is not thread safe
Only luck would prevent another thread from modifying the value of errno between the time when the first thread does something which sets the value of errno and the time when this first thread checks its value.
And...
Of course, in production environments, Murphy's laws apply fully and that nasty scenario would hit you at the worst possible moment. ;)
Re: Simplified Exception Identification in Python
The same as the first comment, thanks, exactly what I needed to know, I was having trouble getting the trace back from errors in a threaded program
Re: Simplified Exception Identification in Python
[to author:] Dude, ever hear of errno?
Re: Simplified Exception Identification in Python
Thanks man, this was exactly the code I was looking for.