view MoinMoin/ @ 3055:29d236eb2ab7

updated underlay
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Wed, 20 Feb 2008 11:07:18 +0100
parents 24bfe5789665
children a48929a5036c
line wrap: on
line source

# -*- coding: iso-8859-1 -*-
""" MoinMoin failure

    Handle fatal errors by showing a message and debugging information.

    @copyright: 2004-2005 Nir Soffer <>
    @license: GNU GPL, see COPYING for details.
import sys, os, logging

from import cgitb
from MoinMoin.error import ConfigurationError
from traceback import extract_tb

class View(cgitb.View):
    """ Display an error message and debugging information

    Additions to cgitb.View:
     - Multiple tracebacks support
     - Debugging information is shown only in debug mode
     - Moin application information
     - General help text and links
     - Handle multiple paragraphs in exception message

    cgitb is heavily modified cgitb, but fully backward compatible with
    the standard cgitb. It should not contain any moin specific code.

    cgitb was refactored to be easy to customize by applications
    developers. This moin specific subclass is an example.
    debugInfoID = 'debug-info'

    def formatContent(self):
        content = (
        return ''.join(content)

    def script(self):
        return '''
<script type="text/javascript">
function toggleDebugInfo() {
    var tb = document.getElementById('%s');
    if (tb == null) return; = ? '' : 'none';
''' % self.debugInfoID

    def stylesheet(self):
        return cgitb.View.stylesheet(self) + """
.cgitb .buttons {margin: 0.5em 0; padding: 5px 10px;}
.cgitb .buttons li {display: inline; margin: 0; padding: 0 0.25em;}

    def formatMessage(self):
        """ handle multiple paragraphs messages and add general help """
        f = self.formatter
        text = [self.formatExceptionMessage(]

        if[0] == ConfigurationError:
            tbt = extract_tb([1].exceptions()[-1][2])[-1]
                f.paragraph('Error in your configuration file "%s"'
                            ' around line %d.' % tbt[:2]))
                f.paragraph("If you want to report a bug, please save "
                            "this page and  attach it to your bug report."))
        return ''.join(text)

    def formatButtons(self):
        """ Add 'buttons' to the error dialog """
        f = self.formatter
        buttons = ['javascript:toggleDebugInfo()',
                          'Show debugging information')]
        if[0] != ConfigurationError:
                          'Report bug'))
                          'Visit MoinMoin wiki'))
        return f.list(buttons, {'class': 'buttons'})

    def formatDebugInfo(self):
        """ Put debugging information in a hidden div """
        attributes = {'id': self.debugInfoID}
        info = [self.debugInfoHideScript(),
                self.formatSystemDetails(), ]
        return self.formatter.section(''.join(info), attributes)

    def debugInfoHideScript(self):
        """ Hide debug info for javascript enabled browsers """
        if self.debug:
            return ''
        return '''
<script type="text/javascript">toggleDebugInfo()</script>

    def formatTraceback(self):
        return self.formatAllTracebacks(self.formatOneTraceback)

    def formatTextTraceback(self):
        template = self.textTracebackTemplate()
        return template % self.formatAllTracebacks(self.formatOneTextTraceback)

    def formatAllTracebacks(self, formatFuction):
        """ Format multiple tracebacks using formatFunction """
        tracebacks = []
        for ttype, tvalue, tb in self.exceptions():
            if ttype is None:
            tracebacks.append(formatFuction((ttype, tvalue, tb)))
            del tb
        return ''.join(tracebacks)

    def exceptions(self):
        """ Return a list of exceptions info, starting at """
            return [] +[1].exceptions()
        except AttributeError:
            return []

    def applicationDetails(self):
        """ Add MoinMoin details to system details """
        from MoinMoin import version
        return ['MoinMoin: Release %s (%s)' % (version.release,

    def formatExceptionMessage(self, info):
        """ Handle multiple paragraphs in exception message """
        text = cgitb.View.exceptionMessage(self, info)
        text = text.split('\n\n')
        text = ''.join([self.formatter.paragraph(item) for item in text])
        return text

def handle(request, err):
    """ Handle failures

    Display fancy error view, or fallback to simple text traceback
    if 'MOIN_DEBUG' in os.environ:
        raise err

    savedError = sys.exc_info()
    logging.error('%s: %s' % (err.__class__.__name__, str(err)), exc_info=savedError)
        debug = 'debug' in getattr(request, 'form', {})
        # default to True here to allow an admin setting up the wiki
        # to see the errors made in the configuration file
        display = True
        logdir = None
        if hasattr(request, 'cfg'):
            display = request.cfg.traceback_show
            logdir = request.cfg.traceback_log_dir
        handler = cgitb.Hook(file=request, display=display, logdir=logdir,
                             viewClass=View, debug=debug)
        printTextException(request, savedError)
        request.write('\nAdditionally cgitb raised this exception:\n')

def printTextException(request, info=None):
    """ Simple text exception that should never fail

    Print all exceptions in a composite error.
    import traceback
    from MoinMoin import wikiutil
    if info is None:
        info = sys.exc_info()
        exceptions = [info] + info[1].exceptions()
    except AttributeError:
        exceptions = [info]
    for info in exceptions:
        text = ''.join(traceback.format_exception(*info))
        text = wikiutil.escape(text)