How to customize constraint violation messages?
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