[Web-SIG] WSGI: catching exception

Ian Bicking ianb at colorstudy.com
Wed Aug 25 08:39:43 CEST 2004

I wrote a couple pieces of middleware that catch exceptions.  One 
defines exceptions like HTTPTemporaryRedirect, so you can raise those 
exceptions and it catches them and turns it into a proper HTTP response. 
  The other catches all unhandled exceptions and formats them with 
cgitb.  (Obviously the two have to be nested in the right order)

Anyway, it felt difficult to handle exceptions, for two reasons:

One place is around the application invocation, looks like:

     return application(environ, start_response)
     blah blah

Except "blah blah" almost certainly depends on whether start_response 
has been called, so it knows if it has to call start_response, or just 
deal with a partially completed response.  So I had to wrap 
start_response in another function that detected if it had been called. 
  This also would create what I believe is a false negative if you were 
comparing start_response at different points in the request, as we 
discussed for certain output-shortcutting extensions.

So, it would be nice if there was an easier way to tell where in the 
request we were, i.e., if headers had been sent.

The other hard part is dealing with the iterator.  I had to wrap the 
iterator, with something like:

def wrap_iter(app_iter):
         for s in app_iter:
             yield s
         blah blah

There we know headers have been sent.  But it's a bit annoying that the 
except has to be done twice.  I was also getting some behavior I have 
yet to understand when I was nesting gzipper and cgitb_catcher, using a 
URL like:


This is using the modules in svn://colorstudy.com/trunk/WSGI (symlinking 
dispatch.py to dispatch.cgi).  Actually, now that I look at it, I think 
it's an issue with gzipper not dealing well with exceptions, though I 
guess that's another exception issue.

Ian Bicking  /  ianb at colorstudy.com  / http://blog.ianbicking.org

More information about the Web-SIG mailing list