CakePHP: catching error in Model->query()
In my recent CakePHP application I use some custom SQL queries that I fire at the database using the $model->query($sql) syntax. Works great, until you have an error in your $sql. I tried the obvious error handling with try … catch:
$this->Model->query('INSERT INTO model WHERE id=invalid');
} catch (exception $ex) {
// exception never happens
}
But the CakePHP Debugger class already catches the error and does it’s handling; which is writing the error to the browser. In my case I need to act upon an error.
After some trial and error (including hacking the core Cake files, which is really dirty) I came up with this: the Cake Debugger class set an error handler using set_error_handler('someErrorHandlingRoutine'). So i made my own error handing routine, borrowing some from the Debugger class:
function handleError($code, $description, $file = null, $line = null, $context = null) {
if (error_reporting() == 0 || $code === 2048 || $code === 8192) {
return;
}
// throw error for further handling
throw new exception(strip_tags($description));
}
}
Now before calling $model->query($sql) I set my custom error handler:
set_error_handler(array($this, 'handleError'));
try {
// execute dangerous sql
$this->Model->query($sql);
} catch (exception $ex) {
// custom error handling here...
}
What it does is simple and ellegant; throw an exception. Now my $model->query code can be wrapped in a try…catch block and if an exception happens I can act on it.

Here’s a very useful tool: 

I’ve
I am a .NET programmer first and foremost. But in my spare time I like to play around with PHP, Erlang, Haskell, F#,