php: autoload exception handling.

Posted by YuriKolovsky on Stack Overflow See other posts from Stack Overflow or by YuriKolovsky
Published on 2010-05-13T13:03:59Z Indexed on 2010/05/13 13:24 UTC
Read the original article Hit count: 248

Filed under:
|
|

Hello again, I'm extending my previous question (Handling exceptions within exception handle) to address my bad coding practice. I'm trying to delegate autoload errors to a 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 is supposed to load a 404 page if the testClass.php file is missing, and it works fine, UNLESS the pageClass.php file is missing as well, in which case I see a

"Fatal error: Class 'pageClass' not found in D:\xampp\htdocs\Test\PHP\errorhandle\index.php on line 29" instead of the "fatal error: 500" message

I do not want to add a try/catch block to each and every class autoload (object creation), so i tried this.

What is the proper way of handling this?

© Stack Overflow or respective owner

Related posts about php

Related posts about autoload