Added errors.lookup() function

This commit is contained in:
Daniele Varrazzo 2018-10-15 00:56:51 +01:00
parent 5da968d6f6
commit e7227ce87b
3 changed files with 18 additions and 0 deletions

View File

@ -56,3 +56,5 @@ idiomatic error handler:
For completeness, the module also exposes all the DB-API-defined classes and For completeness, the module also exposes all the DB-API-defined classes and
:ref:`a few psycopg-specific exceptions <extension-exceptions>` previously :ref:`a few psycopg-specific exceptions <extension-exceptions>` previously
exposed by the `!extensions` module. One stop shop for all your mistakes... exposed by the `!extensions` module. One stop shop for all your mistakes...
.. autofunction:: lookup

View File

@ -10,6 +10,14 @@ from psycopg2._psycopg import (
QueryCanceledError, TransactionRollbackError) QueryCanceledError, TransactionRollbackError)
def lookup(code):
"""Lookup an error code and return its exception class.
Raise `!KeyError` if the code is not found.
"""
return _by_sqlstate[code]
_by_sqlstate = {} _by_sqlstate = {}

View File

@ -54,6 +54,14 @@ class ErrorsTests(ConnectingTestCase):
self.assertEqual(type(e), self.conn.ProgrammingError) self.assertEqual(type(e), self.conn.ProgrammingError)
def test_lookup(self):
from psycopg2 import errors
self.assertIs(errors.lookup('42P01'), errors.UndefinedTable)
with self.assertRaises(KeyError):
errors.lookup('XXXXX')
def test_suite(): def test_suite():
return unittest.TestLoader().loadTestsFromName(__name__) return unittest.TestLoader().loadTestsFromName(__name__)