Created
March 26, 2014 15:35
-
-
Save ionelmc/9786163 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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