10
votes

I was working through a book example on catching exceptions in SQLAlchemy Core using a try/except block:

from sqlalchemy.exc import IntegrityError
ins = insert(users).values(
    username="cookiemon",            #This username is already in db, 
    email_address="[email protected]", 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)

However, I get the following error message:

AttributeError: 'IntegrityError' object has no attribute 'message'

This is verbatim from the book example, why can't I display the error message?

3
You're using python 3? Exceptions don't have the message attribute anymore, they have args. See python.org/dev/peps/pep-0352/#transition-plan - Ilja Everilä
Yes I'm using python 3.5. Ok I just switched to print(error.args) and was able to print the error message. Thanks! - kfolw
should add first comment as answer - danday74

3 Answers

3
votes

In Python3, exceptions no longer have the message attribute, they have args. See python.org/dev/peps/pep-0352/#transition-plan


Credit Ilja Everilä in this comment.

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

Then, replace:

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

with:

print(error)
-1
votes

it's not error.orig.message make it

print(error.message)

will return this

(sqlite3.IntegrityError) NOT NULL constraint failed: users.gender