Opened 4 years ago

Closed 4 years ago

#59 closed enhancement (fixed)

Expose error code as exception attribute or exception type

Reported by: cito Owned by:
Priority: major Milestone: 5.0
Component: DB API 2 Version: 4.1
Keywords: sqlstate error Cc:

Description

The following suggestion has been made by Glyph on the mailing list in 2010-08-30:

As per <http://www.postgresql.org/files/developer/concurrency.pdf> (slide 25, "So you end up needing a retry loop anyway"), pretty much any concurrent PostgreSQL application requires a try/except retry loop somewhere. But, a blanket catch-all retry loop won't be quite right; in many cases, concurrency issues should only cause very specific errors and require specific responses to those error types. For example, if you have a table that might be concurrently INSERTed into, you might want to handle 23505, "UNIQUE VIOLATION", but allow any other error to bubble up and be reported as an unexpected exception, with a logged traceback and all.

The Postgres documentation helpfully enumerates all of these errors (<http://www.postgresql.org/docs/8.4/static/errcodes-appendix.html>) and libpq provides a function to access the error code in a structured, non-localization-sensitive way (PQresultErrorField(res, PG_DIAG_SQLSTATE) http://www.postgresql.org/docs/8.4/static/libpq-exec.html#AEN33971>) but it appears that PyGreSQL doesn't expose this information.

cx_Oracle provides similar information in its .code attribute: <http://cx-oracle.sourceforge.net/html/module.html#exception-handling>. psycopg2 provides exactly this information in its '.pgcode' attribute and named constants to compare against in its 'errorcodes' module: <http://initd.org/psycopg/docs/errorcodes.html#module-psycopg2.errorcodes>. So, despite the fact that this isn't technically standardized in DB-API 2.0, it seems like it is a commonly implemented extension and it would be very nice to have.

Personally my preference would be to actually have a separate exception class for each error code, so that I could do except pg.errors.UniqueViolation:, but that is probably a bunch more work than simply adding an integer attribute.

Change History (2)

comment:1 Changed 4 years ago by cito

See also related tickets #13, #58 and #18.

Last edited 4 years ago by cito (previous) (diff)

comment:2 Changed 4 years ago by cito

  • Resolution set to fixed
  • Status changed from new to closed

This is solved now via the three tickets mentioned above, and also #64 solves the original problem metioned in the ticket description.

Note: See TracTickets for help on using tickets.