Exception handling & Application logging


I am using below code to capture “SQLSTATE 23503: Foreign key violation” error code to display friendly message to end user. Displaying friendly message & everything working fine except it will generate entry under application.log of Yii. It’s:

2012/07/10 19:07:05 [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[23503]: Foreign key violation: 7 ERROR:  update or delete on table "posts" violates foreign key constraint "fk_comments_posts" on table "comments"

DETAIL:  Key (id)=(3041) is still referenced from table "comments".. The SQL statement executed was: DELETE FROM "posts" WHERE "posts"."id"='3041'.

My application code:

try {

   if ($post->delete()) {

      Yii::app()->user->setFlash('success', Yii::t('post', 'The Post has been successfully deleted.'));

      $success = true;

   } else

      Yii::app()->user->setFlash('error',  Yii::t('post', $post->getLastError()));

} catch (Exception $e) {

   if ($e->getCode() == 23503) {

      Yii::app()->user->setFlash('error', Yii::t('post', 'The Post record cannot be deleted. Post already in use.'));

      $success = true;      

   } else

      Yii::app()->user->setFlash('error', Yii::t('post', $e->getMessage()));


if ($success)

   echo 'success';


   echo 'failed';

Could anybody point me what is the mistake I am doing or is this the default behavior of PHP exception handling process? Because I thought if I handling the exception it won’t produce any entries under logs.

Thank you,



You have choice: you should modify database to have a cascading delete from table posts to table comments, or authorize delete of posts after checking that there is no more related comments.

@ragua: Thank you for trying to help me. But I need explanation why Yii log error under application.log though I have handle the exception?

If i understand correctly your question, this is not an exception: from yii, your code is correct and is sent to the database, which meet the problem. That’s why one of the solution is to modify database.

I think I have found the reason for this. Check below explanation:

It’s under this link: Error Handling

No matter we are handling or not the exception Yii always logged the error to application.log when an error occurs.