Replace error message after constraint violation

Is there a way to replace this kind of error message when the user tries do delete a record that is related by ForeignKey of another table (Constraint violation)?

I would like to display a simple message, that the user is able to understand.


I think this wiki can help you. You could use CDbException instead of BusinessExecption in your handler’s class

Thank you.

I tried the suggestion of the wiki article but it did not change anything. I consider this rather complicated for a common task like an error message … ???

Why we cannot do something like this in the controller action?

public function actionDelete($id) {	

   if ( ! $this->loadModel($id)->delete() ) throw new CDbException(500,'Some error message.');

… but this does not work. I am sorry, I am a Yii beginner and not a professional.

Can you print the error message when you run the code below?

public function actionDelete($id) {     

   if ( ! $this->loadModel($id)->delete() ) throw new CDbException(500,'Some error message.');

Throw a CHttpException instead. Check whether you got an errorHandler defined in your config and an controller action to support the display of the error view.

Try using try catch statements to handle any exceptions thrown by your code. Here’s a quick example:



	... database related code goes here (insert, update, or delete)


catch (CDbException $e)


	// Catch any CDbException exceptions coming from Yii

	Yii::app()->user->setFlash('danger', 'A database error has occurred: ' . $e->errorInfo[2]);


catch (Exception $e)


	// Catch all other exceptions

	Yii::app()->user->setFlash('danger', 'An error has occurred: ' . $e->getMessage());


I’m not a hundred percent sure about $e->errorInfo[2] but it should give out the same data as PDO::errorInfo

Sorry, first of all I forgot that I was in DEBUG mode. That’s why I got this long error message. :huh:

In PRODUCTION mode the message is shorter but it containes the SQL command that I don’t want to show the end user and therefore I did this:

In siteController.php I created a shorter message for this kind of DB error:

public function actionError() {


	if ( strpos($error['message'],'Integrity constraint violation') ) {

	    $error['message'] =  "Cannot delete record because it relates to another record.";



	    echo $error['message'];


	    $this->render('error', $error);



In the controller for the view I left the code as originally created by Gii:

public function actionDelete($id) {


    if( ! isset($_GET['ajax']))

 	$this->redirect(isset($_POST['MyReturnUrl']) ? $_POST['MyReturnUrl'] :Yii::app()->user->getState('MyReturnUrl'));


Sorry for the confusion and many thanks for trying to help me.

Check if row can be deleted in model’s beforeDelete(). If not, add an error to the model (simply by (ab)using addError()) and return false. Check the return value of delete() in controller and display errors (getErrors()) when necessary.