我正在开发 Tornado 应用程序。它在一个名为 api.py 的文件中具有 CRUD 函数,相关位显示在此处:
class UserEditException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
def create_user(first_name, last_name, email, password, session = None):
others_with_same_email = session.query(MyAppUser).filter(MyAppUser.email.like(email)).all()
if others_with_same_email is not None:
raise UserEditException('Already another account with that email address.')
这由 app.py 调用,其中包含实际的处理程序,包括用于创建新用户的页面。app.py 的相关位如下所示:
import api
class CreateUserHandler(BaseHandler):
def get(self):
self.render(
local_templates + "/create_user.html",
user_msg = 'Enter new user attributes, including an email address not already in use.',
)
def post(self):
user_msg = '' #currently there are no problems found with inputs
password = self.get_argument("password")
email = self.get_argument("email")
first_name = self.get_argument("first_name",default=None)
last_name = self.get_argument("last_name",default=None)
if user_msg == '':
try:
new_user = api.create_user(first_name, last_name, email, password, agent_uuid = self.current_user)
except api.UserEditException, err:
user_msg = str(err)
else:
user_msg = 'The new user,'+new_user['first_name']+' '+new_user['last_name']+' ('+new_user['email']+') has been created successfully.'
self.render(
local_templates + "/create_user.html",
first_name = first_name,
last_name = last_name,
email = email,
user_msg = user_msg,
)
当我输入一个已经在使用的电子邮件时(即故意触发用户创建错误),我知道在 api.py 中它触发了 UserEditException,因为消息“已经是具有该电子邮件地址的另一个帐户”。正在写入服务器。然后程序崩溃。相反,我希望捕获 UserEditException,并将错误消息放入“user_msg”,以显示到网页。你能指出我在试图捕捉这种错误时可能做错了什么吗?谢谢。