Cakephp 3.x: try catch is not working

Hi all
I want to catch error or exception or PDO exception using php try,catch block in cakephp 3 controller. But this is not working.

Can any one help me that how can i use try and catch block in a controller.

Thanks

You would use it the same way you would in any other PHP code. Are you sure that an exception is being raised? Can you show some code?

1 Like

Hi Jere

I would like to give you many many thanks. Yes i used the following code which raised a PDO exception obviously as i get the error from error log saying that “Unknown artist_order column”

try {
$data = $this->glbl();
$get_group_artists = $data[‘group_artists’]->find(‘all’)
->where([‘group_id’ => $id])
->order([‘artist_order’ => ‘ASC’]);
} catch (PDOException $e) {
$this->log(“Error Occured”, ‘error’);
}
Above code doesn’t write any anything in the error log file. Please assist me how to solve the problem.

Well, time to do some debugging then!

The first thing I would do is throw a debug statement in there, just to be extra sure:

try {
  $data = $this->glbl();
  $get_group_artists = $data['group_artists']->find('all')
    ->where(['group_id' => $id])
    ->order(['artist_order' => 'ASC']);
} catch (PDOException $e) {
  // add this to view the exception details
  debug($e);
  $this->log("Error Occured", 'error');
}

Next, you can check your log setup to make sure your application is configured to log:

// add this somewhere before that code to check out your log setup
foreach (\Cake\Log\Log::configured() as $config) {
    debug(\Cake\Log\Log::config($config));
}
1 Like

In the book it says that the query itself doesn’t not retrieve the results. You must execute with ->all() or ->first()

I’ve run given code in two different ways as you suggested. In addition i have also run my code. All outputs are given in chronological order in the link

image link

  1. foreach (\Cake\Log\Log::configured() as $config) {
    debug(\Cake\Log\Log::config($config));
    }

     try {
         $data = $this->glbl();
         $get_group_artists = $data['group_artists']->find('all')
                 ->where(['group_id' => $id])
                 ->order(['artist_order' => 'ASC']);
     } catch (PDOException $e) {
         // add this to view the exception details
         debug($e);
         $this->log("Error Occured", 'error');
     }
    
  2.  foreach (\Cake\Log\Log::configured() as $config) {
         debug(\Cake\Log\Log::config($config));
     }
    

exit();

    try {
        $data = $this->glbl();
        $get_group_artists = $data['group_artists']->find('all')
                ->where(['group_id' => $id])
                ->order(['artist_order' => 'ASC']);
    } catch (PDOException $e) {
        // add this to view the exception details
        debug($e);
        $this->log("Error Occured", 'error');
    }

$data = $this->glbl();
$get_group_artists = $data[‘group_artists’]->find(‘all’)
->where([‘group_id’ => $id])
->order([‘artist_order’ => ‘ASC’]);