Welcome Guest, Not a member yet? Register   Sign In
Database transaction error handling
#1

I am aware of the discussions on this topic in the CI forum, StackOverflow and elsewhere. I tried to do my research carefully but it seems to me, that I did not find a proper answer.

The question is how to handle database transaction errors and not to loose the error details.

The CI guide suggested way is
PHP Code:
$this->db->trans_start();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->trans_complete();

if (
$this->db->trans_status() === FALSE)
{
 
   // generate an error... or use the log_message() function to log your error


However if 'db_debug' in config/database.php is TRUE, the execution fails on the first failing query and the error handling code is never run.
OK, so let's set 'db_debug' to FALSE. In this case the error handling code runs, but how do I find out more about the DB error (error code and message)? Again, the recommended way is to use $this->db->_error_message() and $this->db->_error_number(), but they return nothing when 'db_debug' is FALSE. And this is my problem. It is not enough to detect an error, I need to know more about it.

I found only this solution to the problem, but I don't like it because it is quite verbose:

PHP Code:
try {
 
 $this->db->trans_begin();
 
 $res $this->db->query('AN SQL QUERY...');
 
 if(!$res) throw new Exception($this->db->_error_message(), $this->db->_error_number());
 
 $res $this->db->query('ANOTHER QUERY...');
 
 if(!$res) throw new Exception($this->db->_error_message(), $this->db->_error_number());
 
 $this->db->trans_commit();
}
catch (
Exception $e) {
 
 $this->db->trans_rollback();
 
 log_message('error'sprintf('%s : %s : DB transaction failed. Error no: %s, Error msg:%s, Last query: %s'__CLASS____FUNCTION__$e->getCode(), $e->getMessage(), print_r($this->main_db->last_query(), TRUE)));


Please not that
- I am using the "manual transaction" mode of CI,
- I have to call $this->db->_error_message(), $this->db->_error_number() after each query, because it returnes an ampty response in the catch block.
Only this way I can achieve the detailed error handling but I find it clunky.

Is there a more elegant way?
Thank you
Reply


Messages In This Thread
Database transaction error handling - by RastoStric - 02-23-2015, 03:03 AM



Theme © iAndrew 2016 - Forum software by © MyBB