【问题标题】:can't catch exception in codeIgniter无法在 codeIgniter 中捕获异常
【发布时间】:2014-05-02 08:54:45
【问题描述】:

对不起我的英语,但我需要帮助 我在尝试捕获插入查询时遇到问题

我有一个表 Employe,有 3 个主键(矩阵、CIN、名称)

我想在添加具有重复值的新员工时捕获异常

我的模特

  function insert_Employe($donnees){
   try{
    $this->db->insert('Employe',$donnees);
    return 'employe enregistré avec succes';
   }catch(Exception $e)
   {
       return $e->getMessage();
   }
}

我的控制器

  function nouveau(){
    if(!$this->offres->_isLogged() || !$this->input->post('Ajax')==1){
        redirect(base_url().'users');
    }
    $values = $this->_get_values();
    try{
    $message = $this->employe->insert_Employe($values);
    echo $message;
    }catch(Exception $e){
        echo $e->getMessage();
    }
}

我无法捕捉到异常

【问题讨论】:

  • 所以$this->db->insert() 导致您在insert_Employe() 中捕获的异常,您想知道为什么后者不抛出异常?
  • 插入重复值时的异常句柄我会捕获此异常以通知用户他必须更改导致问题的重复值

标签: php codeigniter try-catch duplicate-data


【解决方案1】:

这永远不会抛出异常:

$this->db->insert('Employe',$donnees);

所以你永远不会捕捉到这样的异常。如果 insert() 方法失败,如果 $db['default']['db_debug'] 在 database.config 上设置为 TRUE,则会生成自定义错误,否则直接返回 FALSE。

最好的办法是在执行数据库操作时检查错误:

$error = $this->db->_error_message()
if(!empty($error)) {
  throw new Exception('Your message');
}

【讨论】:

    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 2021-08-07
    • 2021-10-14
    • 2019-11-27
    • 2017-03-15
    • 2013-11-23
    • 2017-09-16
    相关资源
    最近更新 更多