I use flash messages to display simple error messages to the user in the event of database error. The full error stack trace gets written to the log. I have found a repeatable issue in which the flash message (and non-flash as well) disappears if the db error is thrown inside of a db transaction.
In my form controller I catch any exception thrown within my model ($this->donation->update() is a library method, which calls a donations_model method)
I write the error to the log (always works) and set a flash message
Then I redirect to another (ledger) controller, which will display the message
Code:
try {
$this->donation->update($transaction_id, $program_id, $friend_id, $gross, $fee, $agency_transaction,
$date, $receipt_number, $donation_revenue, $donation_asset);
} catch (Exception $e) {
//logging works with or without db transaction
log_message('error', $e->getMessage());
//This flash message only remains if db transaction is commented out
$_SESSION['message'] = 'There was an error updating the donation record';
$this->session->mark_as_flash('message');
//The session message can always be echoed here with or without a db transaction
echo $_SESSION['message'];
}
redirect('ledger');
The ledger controller checks for any flash messages. If none, then it sets the message in the view to ''
Code:
//The message is undefined if the error in the model is thrown within a transaction.
// But It prints successfully if the transaction is commented out in the model
echo $_SESSION['message'];
if (isset($_SESSION['message'])) {
$view_content['message'] = $_SESSION['message'];
}
else {
$view_content['message'] = '';
}
Here is the method in the donations_model with a deliberate SQL error (look for 'Hey man!') and a thrown exception
If the transaction is commented out then the flash message will successfully remain in the session and can be displayed on the ledger page
Code:
public function update($transaction_id, $friend_id, $gross, $fee,
$net, $agency_transaction, $receipt_number) {
// Session message remains set if the transaction is commented out
//$this->db->trans_start();
$this->db->where('transaction_id', $transaction_id);
$data = array(
'friend_id' => 'Hey man!', //$friend_id,
'gross' => $gross,
'fee' => $fee,
'net' => $net,
'agency_transaction' => $agency_transaction,
'receipt_number' => $receipt_number
);
if (!$this->db->update('donations', $data)) {
$error = $this->db->error();
throw new Exception('Donations_model->update: ' . $error['code'] . ' ' . $error['message']);
}
//$this->db->trans_complete();
return TRUE;
}
If you need more details for a bug report I can provide a link to my project on github.