On Thu, Jun 24, 2004 at 05:29:54PM -0400, CLIFFORD ILKAY wrote:
> I am trying to trap a SQL error caused by attempting to INSERT a duplicate
> unique key. Here is what I have tried.
>
> #############
> def writeContent(self):
> pr = self.writeln
> newForm = self.form
> if newForm.isSuccessful():
> theTelnumType =
> TelnumType.byDescription(newForm.numType.value())
> if theTelnumType:
> pr('''<p>There is already a Telnum Type =
> '%s'</p>''' % newForm.numType.value())
> else: # not a duplicate so save
> newTelnumType = TelnumType (
> description =
> newForm.numType.value(),
> modUserId = 'cilkay'
> )
> pr('''<p>Successfully saved Telnum Type =
> '%s'</p>''' % newForm.numType.value())
> else:
> #############
>
> So, if I already have a row in telnum_type where description = 'Home', no
> problem, the code above will print out: "There is already a Telnum Type =
> 'Home'". However, if there is no Telnum Type = 'Home', I now get a
> SQLObjectNotFound error raised by SQLObject. If I just try to insert
> without doing a test for a duplicate value, I of course get the usual SQL
> error about violating a unique key constraint. How can I trap SQL errors,
> not just unique key constraint violations, so that I can provide meaningful
> messages to end users?
You want to catch the exception (http://www.python.org/doc/current/tut/node10.html).
You could either leave your test in place and catch the SQLObjectNotFound
exception or skip the test and catch the psycopg.ProgrammingError when you
try to insert the duplicate key.
###########
try:
TelnumType.byDescription(newForm.numType.value())
except SQLObjectNotFound:
TelnumType.new(description = blah, ... )
pr('''<p>Successfully did some stuff</p>''')
###########
I don't like that approach, as it is conceptually ugly (the exception
would be the common case instead of, well, the exception) and you could
accomplish the same thing more efficiently by eliminating the test and
just catching the exception if you try to insert a duplicate.
###########
try:
TelnumType.new(description = blah, ... )
except psycopg.ProgrammingError:
pr('''<p>There is already a Telnum Type = '%s'</p>''' % newForm.numType.value())
###########
Exceptions rock.
-Ben
--
Ben Beuchler There is no spoon.
in...@em... -- The Matrix
|