1.6.3 Creating Custom Handlers

If the built-in handlers don't provide the level of cutomisation you require you can create a custom handler.

Handlers are simply functions which take two dictionaries as parameters. The first parameter will be set as a dictionary containg useful traceback information. The second parameter should be a dictionary with a defualt value of {} which will contain any extra parameters passed to the web.error.handle() function.

For example:

>>> def handler(dict, params={}):
...     print "There was an error."
>>>
>>> import web.error; web.error.handle(handler)
>>> raise Exception('This is an error')
There was an error.

This example isn't too useful. To make it more useful you can make use of the dict parameter as follows:

>>> def handler(dict, params={}):
...     print "There was an error."
...     print dict['textException']
>>>
>>> import web.error; web.error.handle(handler)
>>> raise Exception('This is an error')
There was an error.
Exception: This is an error
    args = ('This is an error',)

As you can see this produces a representation of the exception as text. The dict paramter has the following keys which all do different things:

'text'
Produce a full text output of the error
'html'
Produce a full HTML output of the error
'info'
A tuple of the exception objects (etype, evalue, etb)
'pythonVersion'
A string containing Python version information
'type'
A string containing the type of the exception, for example 'AttributeError' or 'KeyError'
'value'
The error message
'date'
The date and time the error occured
'textException'
The traceback as a multiline string
'htmlException'
The traceback as formatted HTML code
'textCode'
The line of code that produced the error and the neighbouring lines of code, formatted for plain text output
'htmlCode'
The line of code that produced the error and the neighbouring lines of code, formatted for HTML output

Any parameters of the the web.error.handle() function apart from customHandler and context which is used in the preparation of the dict parameter are passed to second parameter of the custom handler as a dictionary.

This means that you can build very powerful handlers.

See About this document... for information on suggesting changes.