Cakephp 3执行最后一次查询

时间:2015-09-06 03:11:33

标签: php mysql cakephp

在查询数据库时,我一直在尝试处理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。

1 个答案:

答案 0 :(得分:0)

Let the PDOException be handled by the error handler (which is done by default). You can setup your own error handler,并在PDOException的情况下发送电子邮件。

您可以使用异常实例$error->queryString获取sql查询。