On Wed, 2013-07-10 at 19:49 -0400, Monty Taylor wrote:
> I'd like top-post and hijack this thread for another exception related
> thing:
> 
> a) Anyone writing code such as:
> 
> try:
>   blah()
> except SomeException:
>   raise SomeOtherExceptionLeavingOutStackContextFromSomeException
> 
> should be mocked ruthlessly.

Ok, mock me ruthlessly then.

Part of designing any API is specifying what predictable exceptions it
will raise. For any predictable error condition, you don't want callers
to have to catch random exceptions from the underlying libraries you
might be calling into.

Say if I was designing an image downloading API, I'd do something like
this:

  https://gist.github.com/markmc/5973868

Assume there's a tonne more stuff that the API would do. You don't want
callers to have to catch socket.error exceptions and whatever other
exceptions might be thrown.

That works out as:

  Traceback (most recent call last):
    File "t.py", line 20, in <module>
      download_image('localhost', 3366, 'foobar')
    File "t.py", line 18, in download_image
      raise ImageDownloadFailure(host, port, path, e.strerror)
  __main__.ImageDownloadFailure: Failed to download foobar from localhost:3366: 
Connection refused

Which is a pretty clear exception.

But I think what you're saying is missing is the stack trace from the
underlying exception.

As I understood it, Python doesn't have a way of chaining exceptions
like this but e.g. Java does. A little bit more poking right now shows
up this:

  http://www.python.org/dev/peps/pep-3134/

i.e. we can't do the right thing until Python 3, where we'd do:

 def download_image(host, port, path):
     try:
         s = socket.create_connection((host, port))
     except socket.error as e:
         raise ImageDownloadFailure(host, port, path, e.strerror) from e

I haven't read the PEP in detail yet, though.

Cheers,
Mark.


_______________________________________________
OpenStack-dev mailing list
OpenStack-dev@lists.openstack.org
http://lists.openstack.org/cgi-bin/mailman/listinfo/openstack-dev

Reply via email to