<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def fancy_error_template_middleware(app):
 """ WGSI middleware for catching errors and rendering the error page. """

    def application(environ, start_response):
        try:
            return app(environ, start_response)
        except Exception as exc:
            sio = StringIO()
            traceback.print_exc(file=sio)
            sio.seek(0)
            response =  Response(
                status=500,
                body=render_error_page(500, exc, traceback=sio.read()),
                content_type="text/html"
            )
            return response(environ, start_response)

    return application