简体   繁体   中英

How to handle exception in Tornado

I am not sure if this is a python question or a Tornado question. But I am struggling to figure out how I can handle an exception if something fails. Here is the snippet of code:

class iQHandler(myBaseHandler):
@tornado.gen.coroutine
def _initialize(self):
    param1 = self.get_argument('media', None)
    if not param1:
        raise tornado.web.HTTPError(404)

    # default the Output parameter to JSON format.
    outputFormat = self.get_argument('output', 'json', False)
    try:
        res = yield self._findfiles(param1)
    except Exception, e:
        # What do I do here?
        print ("Error in _initialize() routine --> ", e)
        # The variable, res, doesn't have any value if there is an exception thrown.
    raise tornado.gen.Return(res)


@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
    response = yield self._initialize()
    self.clear()
    self.finish(response)

How will I go about either raising an exception and returning a value back to the previous routine? Thanks.

This is a python question. The try except block is fine. You can reraise the same exception by saying raise in the except block without anything after raise . That is, replace

raise tornado.gen.Return(res)

by

    raise

Note the indent to keep the raise in the except block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM