Yii2 try...catch not catching exception

I have the following code in a view index.php file.

try {
    $canDelete = (boolean)CallLogUsers::find()->where(['userid' => Yii::$app->user->identity->getId()])->one()->getAttribute('canDelete');
} catch (\Exception $ex) {
    $canDelete = false;
}

The error produced is Call to a member function getAtrribute() on null .

An exception is produced but my catch doesn’t trigger. The error is getting trapped in the Yii2 View.php file and thrown on to the ErrorHandler.php file which finally displays a message and exits.

I know what is causing the error and I just want to set the necessary variable to false and continue but the code in my catch statement never gets executed.

Is there a way that I can trap this error or do I have to rewrite code ?

maybe…

try {
   if (CallLogUsers::find()->where(['userid' => Yii::$app->user->identity->getId()])->exists()){
          $canDelete = (boolean)CallLogUsers::find()->where(['userid' => Yii::$app->user->identity->getId()])->one()->getAttribute('canDelete');
   }else{
      $canDelete = false;
   }
} catch (\Exception $ex) {
    $canDelete = false;
}

This was already answered at SO https://stackoverflow.com/questions/65096209/yii2-php-try-catch-not-triggering-in-view-index-php

1 Like