HowTo: display custom error message when unique index fails on object save
I have add开发者_如何学编程ed an index on a table just to ensure that a set of fields together form a composite unique key (Is this approach correct? or is there a better option with Doctrine?)
After having done that, when I try to save an object and the unique constraint fails, a SQL exception is generated. What is the best way to handle this? and to display a custom error message?
My homework
Check the exception code coming from MySQL & handle it. But if there are multiple such constraints we won't be able to nail down on the exact one
Add a postValidator on the schema, and write the logic in there
Is there a third/better way?
Thanks
try {
$model->save();
// maybe be more precise to catch only that special exception you described
} catch (Doctrine_Exception $e) {
$e->setMessage('my error message');
throw $e;
}
alternatively you could use doctrine's build-in validation...
As proposed earlier, and confirmed by Zolex, the best way is to write a post-validator!
精彩评论