Re: finer exception handling

Karsten Hilbert <[email protected]> Fri, 21 May 2010 23:27:24 +0200
Newsgroups gmane.comp.python.db.psycopg.devel
Message-ID <[email protected]>
On Thu, May 20, 2010 at 03:00:09AM +0100, Daniele Varrazzo wrote:

> > I can't rely on the error messages as my application
> > is multilingual.
> 
> The messages are generated by the database in the language set for the
> backend, see the lc_messages config parameter. Does your application
> really need to publish the error messages from the database to the end
> user?

I would assume the OP meant that because he cannot know the
language those error messages will show up in he cannot
reliably parse the text

We are trying something similar in GNUmed but this only
helps so much:

# =======================================================================
	try:
		conn = dbapi.connect(dsn=dsn, connection_factory=psycopg2.extras.DictConnection)
	except dbapi.OperationalError, e:

		t, v, tb = sys.exc_info()
		try:
			msg = e.args[0]
		except (AttributeError, IndexError, TypeError):
			raise

		msg = unicode(msg, gmI18N.get_encoding(), 'replace')

		if msg.find('fe_sendauth') != -1:
			raise cAuthenticationError, (dsn, msg), tb

		if regex.search('user ".*" does not exist', msg) is not None:
			raise cAuthenticationError, (dsn, msg), tb

		if msg.find('uthenti') != -1:
			raise cAuthenticationError, (dsn, msg), tb

		raise

# =======================================================================
class cAuthenticationError(dbapi.OperationalError):

	def __init__(self, dsn=None, prev_val=None):
		self.dsn = dsn
		self.prev_val = prev_val

	def __str__(self):
		_log.warning('%s.__str__() called', self.__class__.__name__)
		tmp = u'PostgreSQL: %sDSN: %s' % (self.prev_val, self.dsn)
		_log.error(tmp)
		return tmp.encode(gmI18N.get_encoding(), 'replace')

	def __unicode__(self):
		return u'PostgreSQL: %sDSN: %s' % (self.prev_val, self.dsn)

# =======================================================================

> If not you can set the backend language to English and use the
> messages to detect the error.

The problem is that that may not be under your control.

Karsten
-- 
GPG key ID E4071346 @ wwwkeys.pgp.net
E167 67FD A291 2BEA 73BD  4537 78B9 A9F9 E407 1346