我正在尝试捕获事务中的数据库错误,如果发生错误,则回滚并抛出异常。
但是,在抛出异常之前,代码停止并显示db错误屏幕。
任何想法我如何能使它检测db错误而不停止运行后续代码?
try {
$this->my_function($data);
} catch (Exception $e) {
var_dump($e);
}
private function my_function($data)
{
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$this->db->trans_rollback();
throw new Exception('Exception message here...');
}
}
$this->db->trans_complete();
}
这个问题已经有了答案
cwallenpoole的回答:
在application/config/database.php设置
// suppress error output to the screen
$db['default']['db_debug'] = FALSE;
在你的模型或控制器中:
// try the select.
$dbRet = $this->db->select($table, $dataArray);
// select has had some problem.
if( !$dbRet )
{
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
// Do something with the error message or just show_404();
}
或者在你的情况下:
private function my_function($data)
{
$errors = array();
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
array_push($errors, array($errNo, $errMess));
}
}
$this->db->trans_complete();
// use $errors...
}
我相信这个问题有你需要的所有答案,因为它考虑了多次插入,让你完成一次没有返回错误。