Error handling (when foreign key constraint gets hit)

Really basic question:

Discovered today that if you try to delete a record that is associated with another model by foreign key, Yii errors out and displays a not so user-friendly error message.

What I would like to have happen is that the user gets a message saying something like “Sorry, can’t delete a record that is associated with another record in the database… yada yada” and gracefully return back to the screen.

I am using a try { delete } catch { }

but I am pretty sure I am doing this wrong. The try-catch at least prevents the nasty code-based error message, but it doesn’t display a dialog to the user with the message that I would like to display. I’m doing this from within the controller for the model that has the delete action. Probably have to do this across the board for all my models.

Any advice appreciated on best way to handle these. Also, is there a way to set a global configuration variable that says something like if you receive a database exception, for any type of action, just display something like “can’t do this” and return gracefully to the screen in question? I wish Gii just did this automatically.



Can ignore this question. I just didn’t want code to display on the error. Changed from dev to prod in index.php and it hides the error from the user.

‘delete’, like ‘save’ returns true/false indicating the result of the action, so you can detect it like that.