【问题标题】:AttributeError: 'IntegrityError' object has no attribute 'message' SQLAlchemyAttributeError:“IntegrityError”对象没有属性“消息”SQLAlchemy
【发布时间】:2017-07-22 07:28:19
【问题描述】:

我正在阅读有关使用 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'

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

【问题讨论】:

  • 您使用的是 python 3?异常不再具有消息属性,它们具有args。见python.org/dev/peps/pep-0352/#transition-plan
  • 是的,我使用的是 python 3.5。好的,我刚刚切换到 print(error.args) 并且能够打印错误消息。谢谢!
  • 应该添加第一条评论作为答案

标签: python error-handling sqlalchemy


【解决方案1】:

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


信用Ilja Everilä in this comment

【讨论】:

    【解决方案2】:
    def __str__(self):
        return str(self.args[0]
                    if len(self.args) <= 1
                    else self.args)
        
    

    然后,替换:

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

    与:

    print(error)
    

    【讨论】:

    • 您好,波尔图斯,欢迎您。如果您解释您的代码 sn-p 的作用以及它为何有用,未来的人们会感谢您。
    【解决方案3】:

    这不是 error.orig.message 造成的

    print(error.message)
    

    将返回此

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

    【讨论】:

      猜你喜欢
      • 2018-10-04
      • 1970-01-01
      • 2016-01-10
      • 2019-04-27
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 2020-07-08
      相关资源
      最近更新 更多