简体   繁体   中英

How do I catch specific exceptions from pygresql?

I'm trying to improve my error handling, Particularly I would like to handle IntegrityError exceptions from pygresql.

I'm getting the error "NameError: name 'IntegrityError' is not defined" so I need to import something. Is this possible? What do I need to import?

It's definitely possible and almost always advisable to catch the specific exceptions that are thrown by modules you're using.

You're correct that you need to import that specific exception from the package you're using, as it's not part of the python built in exceptions.

Looking at the pygresql docs (around p.88) , it seems that most exceptions are raised from the pgdb module.

Potentially;

from pgdb import IntegrityError

# more code...

try:
  db.insert(obj) # or whatever data access methods you have
except IntegrityError as e:
  # handle the exception
  print(str(e))

Or it maybe the pgdb module is inside the pygresql module so it might be from pygresql.pgdb import IntegrityError . The actual import path may vary, but the syntax will be as above.

After the better part of a day mucking about with this I was able to figure out that the exceptions are defined in the Connection object in pgdb (even if you're using the pg interface). In this case I'm using Flask's @app.errorhandler decorator, but it should still show what needs imported and and how to use it.

from pgdb import Connection

@app.errorhandler(Connection.IntegrityError)
def handle_IntegrityError(e):
  return(str(e), 409)

It would be helpful if pygresql factored these out, as it would make it a lot less confusing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM