Catch database errors before it’s too late

A quiet, little method inside model.php, can actually help us out quite a bit.
I am talking about the onError() callback.
Here’s a snippet from the API:

/**
* Called when a DataSource-level error occurs.
*
* @access public
* @link http://book.cakephp.org/view/1048/Callback-Methods#onError-1056
*/
function onError() {
}

And the little snippet below will log your DB error (presuming you are using ‘default’ connection) as well as the data that can be potentially causing the problem… well that would really depend on the actual error.
Thanks to NetersLandreau for providing the code:

class AppModel extends Model {
public function onError() {
$db = ConnectionManager::getDataSource('default');
$err = $db->lastError();
$this->log($err);
$this->log($this->data);
}
}

Simple, yet very useful. Nice.