error handling in codeigniter
Now this is a rather big debate: Whether you should catch the fatal errors or not. Some say that they are FATAL so you dont know in which condition is the system but I will go with the "try to do the cleanup if the error occured". In order to catch ALL fatal errors you will need to setup a pre_system hook. go to application/config/hooks.php and enter
$hook['pre_system'][] = array(
'class' => 'PHPFatalError',
'function' => 'setHandler',
'filename' => 'PHPFatalError.php',
'filepath' => 'hooks'
);
after that go to hooks directory and add your handling of the error:
<?php
class PHPFatalError {
public function setHandler() {
register_shutdown_function('handleShutdown');
}
}
function handleShutdown() {
if (($error = error_get_last())) {
ob_start();
echo "<pre>";
var_dump($error);
echo "</pre>";
$message = ob_get_clean();
sendEmail($message);
ob_start();
echo '{"status":"error","message":"Internal application error!"}';
ob_flush();
exit();
}
}
as you can see we are using the register_shutdown_function to run a function that checks if an error had occured and if it had send it via email to the developer. This setup is working flawlessly for over 2 years in several CI projects that I have been working with.