Joe14_1990
Joe14_1990

Reputation: 97

How to catch pg8000.core.IntegrityError exception in python?

I am trying to run a test case to catch an primary key exception when trying to load into a table in postgresql using pg8000. But, I'm unable to catch it in python. Below is my code.

import pg8000

def create_albums(self,music):
    experts = []
    exp = music.data_info.get("artist_list")  # List of a dictionary
    try:
        for expert in exp:
            experts.append(ArtistData({
                "name": expert.name,
                "age": expert.age,
                "present": True,
                "nodiscs": expert.get("disc_code")
                }))
    except pg8000.core.IntegrityError:
        raise Exception
    return experts

Below is the error message

pg8000.core.IntegrityError: {'S': 'ERROR', 'V': 'ERROR', 'C': '23505', 'M': 'duplicate key value violates unique constraint "artist_discs_pkey"}

Any help is really appreciated. Thank you.

Upvotes: 0

Views: 1380

Answers (2)

Ben Cooper
Ben Cooper

Reputation: 79

According to the documentation,

"pg8000.core.IntegrityError:" Belongs to the generic (DatabaseError). So you would need to format your code like this replacing IntegrityError with DatabaseError:

import pg8000

def create_albums(self,music):
    experts = []
    exp = music.data_info.get("artist_list")  # List of a dictionary
    try:
        for expert in exp:
            experts.append(ArtistData({
                "name": expert.name,
                "age": expert.age,
                "present": True,
                "nodiscs": expert.get("disc_code")
                }))
    except pg8000.core.DatabaseError:
        raise Exception
    return experts

Upvotes: 0

Gerard H. Pille
Gerard H. Pille

Reputation: 2578

You do catch the exception, but all you do is raise it again, so it's rather useless.

Add a simple print before the raise, eg. print("Failed to insert"), and you'll see that message followed by the exeption that raised it.

Upvotes: 1

Related Questions