1.14.3.2 web.wsgi.error - Error Handling

Error handling middleware is designed to catch any exception which happened lower down the middleware chain and handle the exception in an appropriate way. The WSGI server or runCGI application will handle any exception left uncaught, usually by displaying an HTML page with a message such as "Server Error 500" so error handling middleware is not essential but can be useful for debugging or informational purposes.

The web.wsgi.error module provides one class Error which does not alter the environ dictionary but does catch any exception and print an HTML display of the traceback information. It can also be used to send an email containing a debug output of the error.

import web.wsgi

class simpleApp(web.wsgi.base.BaseApplication):
    def start(self):
        raise Exception('Test Exception')

application = web.wsgi.error.Error(
    simpleApp(),
    emailTo=['james@example.com'], # Enter your email address
    replyName='WSGI Error Example', 
    replyEmail='none@example.com', 
    subject='Error Report',
    sendmail = '/usr/bin/sendmail',  # Specify your sendmail path
    smtp = 'smtp.ntlworld.com',      # or specify an SMTP server and change method to 'smtp'
    method = 'smtp',
)

The error method should return the values status, headers, iterable.

You can test this example by running the WSGI server scripts/WSGIServer.py and visiting http://localhost:8000/error Note: Please remember to modify the sample with your own email address and settings. You will need to restart the WSGIServer after making a change.

You can also create your own error handling class by deriving a middleware class from web.wsgi.error.Error. In this example a text traceback is displayed instead:

import web.wsgi, web.error

def simpleApp(environ, start_response):
    raise Exception('Test Exception')

class myError(web.wsgi.error.Error):
    def error(self):
        "Generate an error report"
        return (
            '200 Error Handled', 
            [('Content-type','text/plain')], 
            [web.error.info(format='text')]
        )

application = myError(
    simpleApp,
)

The error method should return the values status, headers, iterable.

You can test this example by running the WSGI server scripts/WSGIServer.py and visiting http://localhost:8000/errorCustom

Note: We do not need the #!/usr/bin/env python line or modifications to sys.path for WSGI applications since the relevant objects are imported from the files, the files are not executed as scripts.

Errors along the lines of the one shown below may be due to incorrectly formed headers with tuples of the wrong length and can be hard to track down.

ValueError: unpack list of wrong size
      args = ('unpack list of wrong size',)