2015-09-06 32 views
3

我一直在試圖查詢數據庫的時候來處理CakePHP的3例外。CakePHP的3獲得最後的查詢執行

我想獲得時和異常被觸發,通過電子郵件通知到管理員,我使用的MySQL數據庫,所以錯誤代碼將是不錯的太如有可能執行的最後一個查詢。

這是我的代碼現在。

if($this->request->is('post')){ 
    $opciones=$this->request->data; 

    $configsTable = TableRegistry::get('Configs');  

    try{   

    $configsTable->connection()->transactional(function() use($configsTable, $opciones){ 
     foreach ($opciones as $llave => $opcion) { 
     $q = $configsTable->find('all', [ 
      'conditions' => [ 
      'Configs.nombre' => $llave 
      ] 
     ]); 
     $reg = $q->first(); 

     if (empty($reg)) { 
      $data = array(); 
      $data['nombre'] = $llave; 
      $data['valor'] = $opcion; 

      $entity = $configsTable->newEntity($data); 


      if (!$configsTable->save($entity, ['atomic' => false])) { 


      /********trying to catch database error here******/     

      throw new \Exception(__('Error message')); 
      } 

     }else{ 
      $u = $configsTable->updateAll(['valor'=>$opcion], [ 
      'id'=>$reg->id 
      ]); 

      if(!$u){         

      /********trying to catch database error here******/     

      throw new \Exception(__('Error message')); 
      } 
     } 
     } 
    }); 

    $this->Flash->success(__('Ajustes actualizados'),[ 
     'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5] 
    ]); 

    } catch (\PDOException $ex) { 
    $this->Flash->error($ex->getCode().' - '.$ex->getMessage(),[ 
     //'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5] 
    ]); 
    } catch (\Exception $ex){ 
    $this->Flash->error($ex->getMessage(),[ 
     //'params'=>['class'=>'alert-absolute timed', 'tiempo'=>5] 
    ]); 
    } 
} 

我還在食譜上尋找一些信息。 Thaks。

回答

0

PDOException由錯誤處理程序(它在默認情況下完成的)處理。您可以設置your own error handler,檢查異常類型並在PDOException的情況下發送電子郵件。

您可以使用異常實例作爲$error->queryString得到的SQL查詢。