HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How to customize constraint violation messages?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
howviolationcustomizemessagesconstraint

Problem

I want define my own message for each constraint. Is it possible to customize constraint violation messages in PostgreSQL?

Solution

This has been asked in Postgres Forum: Custom Constraint Violation Errors

and after some discussion:


...

So am I got that right, that If I want to have eg custom error messages
for a foreign
key violation, I need to replace all fkeys by trigger functions?!


Michael Musenbrock

answered there:



The short answer is, while it is possible to custom make your
own constraint triggers that emulate foreign keys, don't do it. This
would be a maintenance nightmare.


I'd be more maintainable to catch these errors in your client
application. Here you would reword these error messages according the
business rules of your client application.


Richard Broersma Jr.


with what I think would work best:




It's not hard to create:

CONSTRAINT some_constraint_name FOREIGN KEY col REFERENCES blah(id)




... then in the app, match "some_constraint_name" and map it to a suitable error. That's what I do and it works very well for all constraint types, not just foreign key constraints.


--

Craig Ringer

Code Snippets

CONSTRAINT some_constraint_name FOREIGN KEY col REFERENCES blah(id)

Context

StackExchange Database Administrators Q#20693, answer score: 14

Revisions (0)

No revisions yet.