import sys, cgi

class PrintRawErrors(object):
    """Print EnvironmentErrors of a specified type as preformatted text."""
    def __init__(self, app, type):
        self.app = app
        self.type = type
        
    def __call__(self, environ, start_response):
        try:
            return self.app(environ, start_response)
        except self.type, e:
            if not environ.get('bazjunk.catch_errors',
                               lambda e: False)(environ):
                raise
            exc_info = sys.exc_info()
            start_response('500 Internal Server Error',
                           [('content-type', 'text/html')],
                           exc_info)
            return ["""<html><head><title>500 Internal Server Error</title></head><body><h2>%s with status %s:</h2> <pre>%s</pre></body></html>""" % (type(e).__name__, e.errno, cgi.escape(e.strerror))]
