Php error handling: autoload
I am expanding on my previous question (Handling Exceptions in an Exception Descriptor) to address my poor coding practice. I am trying to delegate autoload errors to an exception handler.
<?php
function __autoload($class_name) {
$file = $class_name.'.php';
try {
if (file_exists($file)) {
include $file;
}else{
throw new loadException("File $file is missing");
}
if(!class_exists($class_name,false)){
throw new loadException("Class $class_name missing in $file");
}
}catch(loadException $e){
header("HTTP/1.0 500 Internal Server Error");
$e->loadErrorPage('500');
exit;
}
return true;
}
class loadException extends Exception {
public function __toString()
{
return get_class($this) . " in {$this->file}({$this->line})".PHP_EOL
."'{$this->message}'".PHP_EOL
. "{$this->getTraceAsString()}";
}
public function loadErrorPage($code){
try {
$page = new pageClass();
echo $page->showPage($code);
}catch(Exception $e){
echo 'fatal error: ', $code;
}
}
}
$test = new testClass();
?>
the above script should load a 404 page if the testClass.php file is missing and it works fine IF the pageClass.php file is also missing, in which case I see
"Fatal error: Class 'pageClass' not found in D: \ xampp \ htdocs \ Test \ PHP \ errorhandle \ index.php on line 29" instead of message "fatal error: 500"
I don't want to add a try / catch block for every class autoload (object creation), so I tried that.
What is the correct way to handle this?
a source to share
Have you tried checking pageClass
early on in the process as it seems like you should even display an error page? If it doesn't exist, and if you don't want to write a 404 page page without any objects (like HTML only), execution bombardment if that class doesn't exist seems like a good way to go.
Hope it helps.
Thanks Joe
a source to share