weberror – Weberror

weberror.errormiddleware

Error handler middleware

class weberror.errormiddleware.ErrorMiddleware(application, global_conf=None, debug=<NoDefault>, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=<NoDefault>, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None, reporters=None, show_error_reason=None)

Error handling middleware

Usage:

error_catching_wsgi_app = ErrorMiddleware(wsgi_app)

Settings:

debug:
If true, then tracebacks will be shown in the browser.
error_email:
an email address (or list of addresses) to send exception reports to
error_log:
a filename to append tracebacks to
show_exceptions_in_wsgi_errors:
If true, then errors will be printed to wsgi.errors (frequently a server error log, or stderr).
from_address, smtp_server, error_subject_prefix, smtp_username, smtp_password, smtp_use_tls:
variables to control the emailed exception reports
error_message:
When debug mode is off, the error message to show to users.
xmlhttp_key:
When this key (default _) is in the request GET variables (not POST!), expect that this is an XMLHttpRequest, and the response should be more minimal; it should not be a complete HTML page.
show_error_reason`:
If set to true and when debug mode is off, exception_type and exception_value are posted after error_message.

Environment Configuration:

paste.throw_errors:
If this setting in the request environment is true, then this middleware is disabled. This can be useful in a testing situation where you don’t want errors to be caught and transformed.
paste.expected_exceptions:
When this middleware encounters an exception listed in this environment variable and when the start_response has not yet occurred, the exception will be re-raised instead of being caught. This should generally be set by middleware that may (but probably shouldn’t be) installed above this middleware, and wants to get certain exceptions. Exceptions raised after start_response have been called are always caught since by definition they are no longer expected.

weberror.evalcontext

class weberror.evalcontext.EvalContext(namespace, globs)

Class that represents a interactive interface. It has its own namespace. Use eval_context.exec_expr(expr) to run commands; the output of those commands is returned, as are print statements.

This is essentially what doctest does, and is taken directly from doctest.

weberror.evalexception

Exception-catching middleware that allows interactive debugging.

This middleware catches all unexpected exceptions. A normal traceback, like produced by weberror.exceptions.errormiddleware.ErrorMiddleware is given, plus controls to see local variables and evaluate expressions in a local context.

This can only be used in single-process environments, because subsequent requests must go back to the same process that the exception originally occurred in. Threaded or non-concurrent environments both work.

This shouldn’t be used in production in any way. That would just be silly.

If calling from an XMLHttpRequest call, if the GET variable _ is given then it will make the response more compact (and less Javascripty), since if you use innerHTML it’ll kill your browser. You can look for the header X-Debug-URL in your 500 responses if you want to see the full debuggable traceback. Also, this URL is printed to wsgi.errors, so you can open it up in another browser window.

class weberror.evalexception.EvalException(application, global_conf=None, error_template_filename=None, xmlhttp_key=None, media_paths=None, templating_formatters=None, head_html='', footer_html='', reporters=None, libraries=None, debug_url_prefix=None, **params)

Handles capturing an exception and turning it into an interactive exception explorer

media(req)

Static path where images and other files live

summary(req)

Returns a JSON-format summary of all the cached exception reports

view(req)

View old exception reports

weberror.formatter

Formatters for the exception data that comes from ExceptionCollector.

class weberror.formatter.AbstractFormatter(show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=(), **kwargs)
filter_frames(frames)

Removes any frames that should be hidden, according to the values of traceback_hide, self.show_hidden_frames, and the hidden status of the final frame.

format_frame_end(frame)

Called after each frame ends; may return None to output no text.

format_frame_start(frame)

Called before each frame starts; may return None to output no text.

long_item_list(lst)

Returns true if the list contains items that are long, and should be more nicely formatted.

pretty_string_repr(s)

Formats the string as a triple-quoted string when it contains newlines.

class weberror.formatter.TextFormatter(show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=(), **kwargs)
class weberror.formatter.HTMLFormatter(show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=(), **kwargs)
class weberror.formatter.XMLFormatter(show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=(), **kwargs)
weberror.formatter.create_text_node(doc, elem, text)
weberror.formatter.html_quote(s)
weberror.formatter.format_html(exc_data, include_hidden_frames=False, **ops)
weberror.formatter.format_text(exc_data, **ops)
weberror.formatter.format_xml(exc_data, **ops)
weberror.formatter.str2html(src, strip=False, indent_subsequent=0, highlight_inner=False, frame=None, filename=None)

Convert a string to HTML. Try to be really safe about it, returning a quoted version of the string if nothing else works.

weberror.formatter._str2html(src, strip=False, indent_subsequent=0, highlight_inner=False, frame=None, filename=None)
weberror.formatter.truncate(string, limit=1000)

Truncate the string to the limit number of characters

weberror.formatter.make_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\'')
weberror.formatter.make_pre_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\'')

Like make_wrappable() but intended for text that will go in a <pre> block, so wrap on a line-by-line basis.

weberror.reporter

class weberror.reporter.Reporter(**conf)
class weberror.reporter.EmailReporter(**conf)
class weberror.reporter.LogReporter(**conf)
class weberror.reporter.FileReporter(**conf)
class weberror.reporter.WSGIAppReporter(exc_data)

weberror.collector

An exception collector that finds traceback information plus supplements

class weberror.collector.ExceptionCollector(limit=None)

Produces a data structure that can be used by formatters to display exception reports.

Magic variables:

If you define one of these variables in your local scope, you can add information to tracebacks that happen in that context. This allows applications to add all sorts of extra information about the context of the error, including URLs, environmental variables, users, hostnames, etc. These are the variables we look for:

__traceback_supplement__:

You can define this locally or globally (unlike all the other variables, which must be defined locally).

__traceback_supplement__ is a tuple of (factory, arg1, arg2...). When there is an exception, factory(arg1, arg2, ...) is called, and the resulting object is inspected for supplemental information.

__traceback_info__:
This information is added to the traceback, usually fairly literally.
__traceback_hide__:

If set and true, this indicates that the frame should be hidden from abbreviated tracebacks. This way you can hide some of the complexity of the larger framework and let the user focus on their own errors.

By setting it to 'before', all frames before this one will be thrown away. By setting it to 'after' then all frames after this will be thrown away until 'reset' is found. In each case the frame where it is set is included, unless you append '_and_this' to the value (e.g., 'before_and_this').

Note that formatters will ignore this entirely if the frame that contains the error wouldn’t normally be shown according to these rules.

__traceback_reporter__:
This should be a reporter object (see the reporter module), or a list/tuple of reporter objects. All reporters found this way will be given the exception, innermost first.
__traceback_decorator__:
This object (defined in a local or global scope) will get the result of this function (the CollectedException defined below). It may modify this object in place, or return an entirely new object. This gives the object the ability to manipulate the traceback arbitrarily.

The actually interpretation of these values is largely up to the reporters and formatters.

collect_exception(*sys.exc_info()) will return an object with several attributes:

frames:
A list of frames
exception_formatted:
The formatted exception, generally a full traceback
exception_type:
The type of the exception, like ValueError
exception_value:
The string value of the exception, like 'x not in list'
identification_code:
A hash of the exception data meant to identify the general exception, so that it shares this code with other exceptions that derive from the same problem. The code is a hash of all the module names and function names in the traceback, plus exception_type. This should be shown to users so they can refer to the exception later. (@@: should it include a portion that allows identification of the specific instance of the exception as well?)

The list of frames goes innermost first. Each frame has these attributes; some values may be None if they could not be determined.

modname:
the name of the module
filename:
the filename of the module
lineno:
the line of the error
revision:
the contents of __version__ or __revision__
name:
the function name
supplement:
an object created from __traceback_supplement__
supplement_exception:
a simple traceback of any exception __traceback_supplement__ created
traceback_info:
the str() of any __traceback_info__ variable found in the local scope (@@: should it str()-ify it or not?)
traceback_hide:
the value of any __traceback_hide__ variable
traceback_log:
the value of any __traceback_log__ variable

__traceback_supplement__ is thrown away, but a fixed set of attributes are captured; each of these attributes is optional.

object:
the name of the object being visited
source_url:
the original URL requested
line:
the line of source being executed (for interpreters, like ZPT)
column:
the column of source being executed
expression:
the expression being evaluated (also for interpreters)
warnings:
a list of (string) warnings to be displayed
getInfo:
a function/method that takes no arguments, and returns a string describing any extra information
extraData:
a function/method that takes no arguments, and returns a dictionary. The contents of this dictionary will not be displayed in the context of the traceback, but globally for the exception. Results will be grouped by the keys in the dictionaries (which also serve as titles). The keys can also be tuples of (importance, title); in this case the importance should be important (shows up at top), normal (shows up somewhere; unspecified), supplemental (shows up at bottom), or extra (shows up hidden or not at all).

These are used to create an object with attributes of the same names (getInfo becomes a string attribute, not a method). __traceback_supplement__ implementations should be careful to produce values that are relatively static and unlikely to cause further errors in the reporting system – any complex introspection should go in getInfo() and should ultimately return a string.

Note that all attributes are optional, and under certain circumstances may be None or may not exist at all – the collector can only do a best effort, but must avoid creating any exceptions itself.

Formatters may want to use __traceback_hide__ as a hint to hide frames that are part of the ‘framework’ or underlying system. There are a variety of rules about special values for this variables that formatters should be aware of.

TODO:

More attributes in __traceback_supplement__? Maybe an attribute that gives a list of local variables that should also be collected? Also, attributes that would be explicitly meant for the entire request, not just a single frame. Right now some of the fixed set of attributes (e.g., source_url) are meant for this use, but there’s no explicit way for the supplement to indicate new values, e.g., logged-in user, HTTP referrer, environment, etc. Also, the attributes that do exist are Zope/Web oriented.

More information on frames? cgitb, for instance, produces extensive information on local variables. There exists the possibility that getting this information may cause side effects, which can make debugging more difficult; but it also provides fodder for post-mortem debugging. However, the collector is not meant to be configurable, but to capture everything it can and let the formatters be configurable. Maybe this would have to be a configuration value, or maybe it could be indicated by another magical variable (which would probably mean ‘show all local variables below this frame’)

class weberror.collector.ExceptionFrame(**attrs)

This represents one frame of the exception. Each frame is a context in the call stack, typically represented by a line number and module name in the traceback.

get_source_line(context=0)

Return the source of the current line of this frame. You probably want to .strip() it as well, as it is likely to have leading whitespace.

If context is given, then that many lines on either side will also be returned. E.g., context=1 will give 3 lines.

weberror.collector.collect_exception(t, v, tb, limit=None)

Collection an exception from sys.exc_info().

Use like:

try:
    blah blah
except:
    exc_data = collect_exception(*sys.exc_info())