php custom error handling
When i first learnt php i was unemployed and started to teach myself the basics with every spare moment i had. This helped me considerably when i actually got a job in the industry as i was already comfortable with the language and was looking to move on. When i started work i decided to do this by taking each project i had to do and making sure that i did at least 1 new thing i didn’t already know or 1 improvement on my last project. Whether i think about it or not this is still something i do and i think its something every developer does they aspire to make better, faster code and to make it easier for them to impliment in the future. Anyway one of my early improvements when i was using mostly procedural code was to create a custom error handler. I had read about this in one of my books i had taught myself from but never put it in place. A new project was in the wings and i was ready to try it out. For any budding php developers heres what i created..?
<?php
function errorHandler ($e_number, $e_message, $filename, $linenum, $vars)
{
$errortype = array (
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parsing Error',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'User Error',
E_USER_WARNING => 'User Warning',
E_USER_NOTICE => 'User Notice',
);
if(substr(phpversion(),0,1) > 4) {
$errortype[E_STRICT] = 'Runtime Notice';
}
$message = $errortype[$e_number].' : An error occurred in script ' .$filename. ' on <span style="color: blue;">line ' .$linenum. '</span> : <span style="color: green;">'.$e_message.'<span>';
echo '<div style="padding: 5px; left: 0px; border: 1px solid red; z-index: 99999; background: #FFF;"><span style="padding: 5px; color: red; font-size: 12px; font-family: tahoma;">'. $message. '</span></div>';
}
set_error_handler('errorHandler');
?>
Ok so it might not be the most pretty looking code but the output isn’t too shabby and i actually found it alot easier to pick out the specifics of the errors faster. Not only that but i think it also made sure that i didn’t complete a site without fixing any warnings or errors still showing as it was so clear to see it would be impossible to present it to a client with an error showing like this. Note that the code uses inline styles as i didn’t want to rely on a stylesheet when transferring the code between projects. It was also built for php4 at the time but was modified over time to include the strict notice for php5. Enjoy.
Comments
Comments are currently closed