Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
from tornado import ioloop
from tornado import web
from tornado import gen
from tornado.httpclient import AsyncHTTPClient
from functools import wraps
from inspect import isgeneratorfunction
def error_handling(func):
if isgeneratorfunction(func):
@wraps(func)
def error_handling_wrapper_gen(self, *args, **kwargs):
try:
gener = func(self, *args, **kwargs)
val = yield gener.next()
try:
while True:
val = yield gener.send(val)
except StopIteration:
return
except Exception as exc:
self.write('{"error": %r}' % repr(exc))
self.finish()
return error_handling_wrapper_gen
else:
@wraps(func)
def error_handling_wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except Exception as exc:
self.write('{"error": %r}' % repr(exc))
self.finish()
return error_handling_wrapper
class GenHandler(web.RequestHandler):
@gen.coroutine
@error_handling
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
self.write(response.body)
class NormalHandler(web.RequestHandler):
@error_handling
def get(self):
self.write("yeeep")
class GenHandlerError(web.RequestHandler):
@gen.coroutine
@error_handling
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
raise Exception("Crappo The Magician")
class NormalHandlerError(web.RequestHandler):
@error_handling
def get(self):
raise Exception("Crappo The Magician")
application = web.Application([
(r"/gen", GenHandler),
(r"/normal", NormalHandler),
(r"/gen-error", GenHandlerError),
(r"/normal-error", NormalHandlerError),
])
if __name__ == "__main__":
application.listen(8888, '0.0.0.0')
ioloop.IOLoop.instance().start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.