Source code for uw.web.wsgi.errors

"""HTTP status code reporting.

A WSGI handler which delegates to a wrapped handler.  If the wrapped handler
does not throw an HTTP status exception, then the wrapped handler is
responsible for producing the WSGI response.  Alternately, the wrapped handler
may throw an HTTP status exception, in which case the handler in this module
will produce an appropriate HTTP result based on the HTTP status.
"""

import functools

from ll.xist.ns import html

from . import function, parameter, status

return_html = functools.partial (function.return_html,
 use_set_status=True, use_add_header=True)

@parameter.use_environ_param
@return_html
def simple_error_handler (environ, set_status, add_header, exception, **params):
    """A simple handler to report HTTP errors as HTML error document pages.

    Wrapped immediately after definition so the result is a WSGI handler.

    Sets the HTTP status according to the exception obtained from the context.
    Adds headers determined by the exception.  Finally returns an HTML
    document obtained from the exception.

    *** TODO: Include meaningful information in the HTTP document body.
    """
    set_status (exception.get_status ())
    for header in exception.get_headers (environ):
        add_header (header)
    return exception.get_status (), exception.get_body ()

[docs]def handle_errors (handler, error_handler=simple_error_handler): """Return a WSGI handler to report error exceptions as HTTP errors. Parameters: handler -- inner handler to invoke first; error_handler -- handler to invoke in case an HTTP error is raised. This function computes a WSGI handler. The returned handler first invokes handler, returning its result if it completes successfully. If the inner handler fails with an HTTP error, the exception is stored in the context and error_handler is invoked. By default error_handler is simple_error_handler which produces a simple HTML document determined by the exception. If the inner handler returns an HTTP status, also represented as an exception, a response with no body is produced. This is useful for HTTP redirects. If an exception occurs that is not defined in the status module, it propagates without being caught. If this can happen, it may be appropriate to catch the exception and instead raise an HTTP Internal Server Error. """ def result (environ, start_response): try: return handler (environ, start_response) except status.HTTPError as x: parameter.set_param (environ, 'exception', x) return error_handler (environ, start_response) except status.HTTPStatus as x: start_response (x.get_status (), x.get_headers (environ)) return [] return result