[Twisted-web] [Nevow] custom renderers for exceptions

Manlio Perillo manlio_perillo at libero.it
Mon Aug 7 13:25:26 CDT 2006


Hi.

I have written this code to write custom "resource handlers" for exceptions.

Using adapters directly avoids the use of the context.


class DefaultExceptionHandler(object):
    # TODO catch all error handling

    implements(inevow.ICanHandleException)

    def renderHTTP_exception(self, ctx, reason):
        def cb(html):
            request.write(html)
            request.finishRequest(False)

        log.err(reason)

        request = inevow.IRequest(ctx)
        error = reason.value

        # make error available to the adapter
        request.error = error
        rend = inevow.IResource(error)
        rend.renderHTTP(ctx).addCallback(cb)


# replace the default one
appserver.DefaultExceptionHandler = DefaultExceptionHandler



class ExceptionResource(Adapter, rend.Page):
    docFactory = loaders.stan(
        t.html[
            t.head[
                t.title["Oops"]
                ],
            t.body[
                t.p(render=t.directive("string"))
                ]
            ]
        )


class ZeroDivisionResource(Adapter, rend.Page):
    implements(inevow.IRenderer)
    docFactory = loaders.stan(
        t.html[
            t.head[
                t.title["Oops"]
                ],
            t.body[
                t.p[
                    t.xml("∞")
                    ]
                ]
            ]
        )



registerAdapter(ExceptionResource, Exception, inevow.IResource)
registerAdapter(ZeroDivisionResource, ZeroDivisionError, inevow.IResource)



Example:

class OopsPage(rend.Page):
    def exception(self, ctx, data):
        1/0 # cause an exception on purpose

    docFactory = loaders.stan(exception)




Regards  Manlio Perillo



More information about the Twisted-web mailing list