AttributeError:'IntegrityError'对象没有属性'message'SQLAlchemy

时间:2017-03-02 14:09:53

标签: python error-handling sqlalchemy

我正在编写一个关于使用try / except块在SQLAlchemy Core中捕获异常的书籍示例:

from sqlalchemy.exc import IntegrityError
ins = insert(users).values(
    username="cookiemon",            #This username is already in db, 
    email_address="damon@cookie.com", should throw an IntegrityError 
    phone="111-111-1111",             for violating unique constraint
    password="password"
    )
try:
    result=connection.execute(ins)
except IntegrityError as error:
    print(error.orig.message, error.params)

但是,我收到以下错误消息:

  

AttributeError:'IntegrityError'对象没有属性'message'

这是书中的示例,为什么我不能显示错误信息?

3 个答案:

答案 0 :(得分:2)

在 Python3 中,异常不再具有 message 属性,它们具有 args。参见 python.org/dev/peps/pep-0352/#transition-plan


贷记 Ilja Everilä 中的 this comment

答案 1 :(得分:0)

不是错误。orig.message制作

print(error.message)

将返回此

(sqlite3.IntegrityError)NOT NULL约束失败:users.gender

答案 2 :(得分:0)

def __str__(self):
    return str(self.args[0]
                if len(self.args) <= 1
                else self.args)
    

然后,替换:

print(error.orig.message, error.params)

与:

print(error)