【发布时间】:2019-07-24 08:24:56
【问题描述】:
tornado 应用程序中处理程序之外的函数中引发的错误被传递给处理程序内部的@gen.coroutine 修饰函数,捕获的异常显示在控制台中但未显示在应用程序中(例如在 POSTMAN 中)
以下是声明的自定义异常集
class ApplicationError(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
super(Exception, self).__init__(message)
class ServerError(ApplicationError):
def __init__(self):
ApplicationError.__init__(self, "Server Connection NOT Established", 500)
class InvalidTenantID(ApplicationError):
def __init__(self):
ApplicationError.__init__(self,"Either TenantID or ModelID is incorrect" , 404)
class InvalidPayloadPOSTError(ApplicationError):
def __init__(self):
ApplicationError.__init__(self,"Payload Mismatch",400)
现在处理程序有
class MyHandler(RequestHandler):
@gen.coroutine
def post(self, model_id):
try:
data = tornado.escape.json_decode(self.request.body)
yield self.predict('mod1')
except ApplicationError as e:
self.respond(e.message, e.code)
except Exception:
error = ServerError()
self.respond(error.message, error.code)
@gen.coroutine
def predict(self, mod):
model = mod(load from database)
try:
values = (load from database)
except ApplicationError as e:
logger.warning(e.message, e.code)
except Exception:
error = InvalidPayloadPOSTError()
logger.warning(error.message, error.code)
results = yield self._b_run(model, values)
self.respond(results)
def respond(self, data, code=200):
self.set_status(code)
self.write(data)
外部处理程序我有 mod 函数(在处理程序中的预测内部调用)
def mod(model):
try:
elastic_model = es.get(index = "index_name", doc_type='doc',id = model)
except ApplicationError as e:
logger.warning(e.message, e.code)
except Exception as error:
logger.error(traceback.format_exc())
logger.info('Either Tenant_id or Model_id NOT Found')
error = InvalidTenantID()
print(error)
logger.warning(error.message, error.code)
这里如果mod函数中的elastic_model抛出错误,会抛出InvalidTenantID的异常并在控制台显示,但在应用程序(POSTMAN)中显示post方法中ServerError()的消息,
此外,如果在 predict 方法中发生异常,则 InvalidPayloadPOSTError() 的消息会显示在控制台中,而不是应用程序中,则会显示 ServerError() 的消息。
应该如何抓取其他函数的异常,我知道@gen.coroutine装饰器终于出结果了。
【问题讨论】:
标签: tornado