Handling errors

Once in a while, you might have to catch an error. Of course, this is also possible in Python. The following example shows how this works:

CREATE OR REPLACE FUNCTION trial_error()  
  RETURNS text  AS 
$$ 
try: 
  rv = plpy.execute("SELECT surely_a_syntax_error") 
except plpy.SPIError: 
  return "we caught the error" else: 
else: 
  return "all fine" 
$$ LANGUAGE 'plpythonu'; 

You can use a normal try/except block and access plpy to treat the error you want to catch. The function can then return normally without destroying your transaction, as follows:

test=# SELECT trial_error(); 
trial_error --------------------- we caught the error (1 row)

Remember, PL/Python has full access to the internals of PostgreSQL. Therefore, it can also expose all kinds of errors to your procedure. Here is an example:

except spiexceptions.DivisionByZero: 
  return "found a division by zero"  
except spiexceptions.UniqueViolation:  
  return "found a unique violation" 
except plpy.SPIError, e: 
  return "other error, SQLSTATE %s" % e.sqlstate 

Catching errors in Python is really easy and can help prevent your functions from failing.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset