Hello all, How do you guys handle database error i...
# python
p
Hello all, How do you guys handle database error in python? I’m getting a “key already exists error” (which is wanted) but from that I’d like to make an if statement. How’d I go about that?
z
What is the behavior you are trying to achieve?
p
@zachtsk Depending on the error it’d dehave differently: If the API error is a duplicate key => log Duplicate otherwise log the error message. I have achieved that by turning the error into a string and simple checking if the “key already exists” string was in it
a
can you send your code and the error that's being raised? @ProtoFeather
i believe an APIError should be being raised, which you can just
try: ... except
p
Copy code
for item in api_list:
        try:
            supabase.table("suchmeme").insert(item).execute()
            print(f'Inserted meme {item["id"]} to Supabase DB')
            post(item)
        except Exception as e:
            print(e)
            if 'duplicate key value violates unique constraint' in str(e):
                print("Meme already exists")
                continue
            else:
                print(f'Error upon inserting data in DB with meme {item["id"]} due to {e}')
                continue
that's my code and here's the error I get:
{'message': 'duplicate key value violates unique constraint "suchmeme_pkey"', 'code': '23505', 'details': 'Key (id)=(6396) already exists.', 'hint': None}
the error is of type
<class 'postgrest.exceptions.APIError'>
a
Aha yeah, we only have a single error class for all API errors, making separate ones are something that's on our todo list
For now you can just specifically except just the postgrest_py.APIError instead of the catch-all
except Exception
I believe you can also just check the error code (it should be 23505 always for this specific error I think)
Copy code
py
...
except APIError as e:
    if e.code == "23505":
        # do stuff
p
Great! Thanks for the tip!
2 Views