postgresql-simple icon indicating copy to clipboard operation
postgresql-simple copied to clipboard

Parsing of (trigger?) error messages

Open jonkri opened this issue 10 years ago • 7 comments

I don't know if this is a good idea or not, but it would be nice if postgresql-simple could aid in parsing PostgreSQL error messages. In our case, we would like to see some higher-level representation of the error message informing that a trigger has violated a constraint. As it is right now, it seems like each application receiving these error messages will have to parse these message strings separately.

Thanks for a great library!

jonkri avatar Jul 17 '15 19:07 jonkri

There's already some support for that in the Errors module. You might find the discussion in #22 and #23 informative.

lpsmith avatar Jul 17 '15 20:07 lpsmith

I've been raising exceptions in my triggers using messages that look similar to one of the 4 constraint violations (unique, not null, check, foreign key). This allows me to take advantage of the Errors module already mentioned.

CREATE OR REPLACE FUNCTION table_name_constraint_trigger() RETURNS TRIGGER AS $$
BEGIN
    IF true THEN
        RAISE EXCEPTION 'new row for relation "table_name" violates check constraint "table_constraint_name_check"' USING ERRCODE = 'check_violation';
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE 'plpgsql';

Within my application, I have a "mapping" containing all of the constraint violations and a pretty error message to send the user. It's not great, but it works. Not sure how closely the message has to match for it to be caught as a ConstraintViolation, though.

cimmanon avatar Jul 17 '15 21:07 cimmanon

That sounds like a reasonable suggestion, Cinnamon. Thank you.

Also, functions in the Errors module are particularly simple, so it really shouldn't be difficult to write one of your own. If you have some additional errors that you would like to have handled, I'd gladly entertain a pull request.

lpsmith avatar Jul 20 '15 03:07 lpsmith

I want to add that postgresql 9.3 has extra fields returned on error which contain same info as parsed by Errors module. So maybe postgresql-simple should take advatage of it and use message parsing as fallback for earlier versions.

sopvop avatar Jul 20 '15 09:07 sopvop

Well the issue there is we need two forms of fallback; one for when libpq doesn't support the function, another when the backend doesn't.

Or we can wait another 3-5 years before I'm ready to cut off support for libpq-9.0, 9.1, and 9.2, then we only need one form of fallback. :-/

lpsmith avatar Jul 20 '15 17:07 lpsmith

Although, I would admit, if somebody got a patch into libpq that allowed us to request the textual/binary formats on a column-by-column basis, I'd be willing to require that version of libpq (9.5? 9.6?) much sooner than I normally would.

lpsmith avatar Jul 20 '15 17:07 lpsmith

Or we can wait another 3-5 years [...]

It's been 3 years :grin:

bitc avatar Apr 21 '18 19:04 bitc