Thread: Can I map "raise XXX" to some custom python exceptions?
Right now, I have some triggers that can raise integrity constraint violations. And in python, I have code like this: try: cursor.execute("...") except dbconn.InternalError, ex: I'm working on code that handles buying and selling physical goods. It would be nice to have exceptions that are more relevant to that stuff -- I mean I want exceptions like "this good is not in the warehouse" or "this good isn't available during that window of time". Is this possible? How do I map database exceptions to interesting exception types in python? Matt -- W. Matthew Wilson matt@tplus1.com http://tplus1.com
On Sun, Jun 19, 2011 at 1:02 PM, Dan Halbert <halbert@halwitz.org> wrote: > Is it that you don't just want to raise your own exceptions manually, e.g.: > > try: > cursor.execute("...") > except dbconn.InternalError, ex: > if ... : > raise OutOfStockException(...) Yeah, this is what I'm doing now. But there's a good chance that something is going to get mapped to the OutOfStockException when it is really a completely different kind of exception, like maybe I forgot to set a non-null column. So, really, I want to be able raise specific exceptions within postgresql, and then define how those are converted to python objects. Maybe I need to verify that postgresql supports custom exceptions. Matt -- W. Matthew Wilson matt@tplus1.com http://tplus1.com
On Sun, Jun 19, 2011 at 6:45 PM, W. Matthew Wilson <matt@tplus1.com> wrote: > So, really, I want to be able raise specific exceptions within > postgresql, and then define how those are converted to python objects. It is an interesting use case. I've recently written a Postgres-based program where I've used a specific sqlcode for the exceptions. It would be nice having a mapping errcode->python exception instead of using a pattern of catching and re-throwing. However I suspect it wouldn't be a complete solution: still with my specific example in mind, half of the exceptions are raised from PL/pgSQL functions or triggers, where I have control over the errcode. But other errors are generated by database-handled integrity violations, so I don't see a way to generate an uniform errcode throughout all the applications. -- Daniele