Scripting - How to catch Raise from db function

I’m on 8.1.20

I have a PostgreSQL DB with functions that RAISE exception, I search the way to catch the RAISE message (highlighted)

Database errors come through to ignition as java errors so you should use java.lang.Exception or preferably java.lang.Throwable to catch them like

import java.lang.Throwable
    # some sql operation
except java.lang.Throwable, e:
    # catch exception

You may then want to examine e.cause to see the specific error. I use this to good effect.


I havent used cause before, but I tend to use:

import traceback

Also, I use

from java.lang import Throwable

except Throwable:
   import traceback....

It just avoids repeating things a bit

1 Like

The reason I like e.cause is its the exact error which allows me to easily catch for certain expected errors (my application is all forms so I have to expect Users to mess up)

so it allows me to do something like this

			if 'Duplicate entry' in str(e.cause):
				message = self.parseUniqueConstraintViolationErrorMessage(e, action)
			elif 'cannot be null' in str(e.cause):
				message = self.parseNullMessage(e, action)
			elif "Data too long" in str(e.cause):
				message = self.parseTooLongMessage(e, action)
			elif "Cannot delete or update a parent row" in str(e.cause) or "Cannot add or update a child row" in str(e.cause):
				message = self.parseFKConstraintMessage(e, action)
			elif "EmptyStringError" in str(e.cause):
				# Custom error we throw from the database via string.  Error messages look like "EmptyStringError, rest of message here"
				message = self.parseEmptyStringError(e, action)

Then in my else is where I will log the entire stack trace as it's an unexpected database error.

1 Like