我有以下代码会不断触发ERROR:tornado.application:Uncaught exception GET
,但似乎无法弄清楚如何正确处理它?
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, id):
http = tornado.httpclient.AsyncHTTPClient()
endpoint = "https://www.foobar.com/api/v1"
foo = yield http.fetch("{}/foo/{}".format(endpoint, id), self._handle_fetch)
bar = yield http.fetch("{}/bar/{}".format("http://www.doh.com", id), self._handle_fetch)
// do other things at this point like serve content to user
def _handle_fetch(self, response):
if response.error:
print("there was an error so returning None")
return {}
else:
print("everything OK so returning response")
return response
foo yield将成功,而bar yield将失败
如何处理异常(exception)情况,以便在小节合格率失败时继续向用户提供内容? (因为我不在乎它是否成功)
更新
我设法处理了这个错误:
try:
foo = yield http.fetch("{}/foo/{}".format(endpoint, id), self._handle_fetch)
bar = yield http.fetch("{}/bar/{}".format("http://www.doh.com", id), self._handle_fetch)
print(foo.body)
print(bar.body)
except tornado.httpclient.HTTPError as e:
print("Error: " + str(e))
except Exception as e:
print("Error: " + str(e))
但是我试图找出如何识别导致失败的
fetch
,因为如果foo
成功并且bar fails. But if
foo`失败,我仍然想尝试并继续提供内容我想使整个响应失败并发送自定义错误
最佳答案
好的,我设法解决了这个问题:
import tornado.ioloop
import tornado.web
import tornado.httpclient
import html2text
import json
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self, id):
http = tornado.httpclient.AsyncHTTPClient()
endpoint = "https://www.foo.com/api/v1"
try:
foo = yield http.fetch("{}/foo/{}".format(endpoint, id))
bar = yield http.fetch("{}/bar/{}".format("http://www.doh.com", id))
except tornado.httpclient.HTTPError as e:
if "bar" in e.response.effective_url:
bar = "change bar value"
else:
foo = "change foo value"
self._response(foo, bar)
def _response(self, foodict, bardict):
self.write("...")
self.finish()
if __name__ == "__main__":
application = tornado.web.Application([
(r"/api/v1/foobar/(\d{7})/?", MainHandler),
])
application.listen(8888)
tornado.httpclient.AsyncHTTPClient.configure("tornado.simple_httpclient.SimpleAsyncHTTPClient", max_clients=2, defaults=dict(connect_timeout=float(10), request_timeout=float(100)))
tornado.ioloop.IOLoop.current().start()
关于python - 如何处理Python错误:tornado.application:Uncaught exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36908662/