代码之家  ›  专栏  ›  技术社区  ›  Timo Huovinen

php:autoload异常处理

  •  2
  • Timo Huovinen  · 技术社区  · 15 年前

    我将扩展我以前的问题(在异常处理中处理异常),以解决我的错误编码实践。 我正在尝试将自动加载错误委托给异常处理程序。

    <?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();
    ?>
    

    如果testclass.php文件丢失,那么上面的脚本应该加载404页,并且它工作正常,除非pageclass.php文件也丢失,在这种情况下,我看到

    “致命错误:在第29行的d:\xampp\htdocs\test\php\errorhandle\index.php中找不到类”pageclass“,而不是“致命错误:500”消息

    我不想向每个类自动加载(对象创建)添加一个try/catch块,所以我尝试了这个方法。

    正确的处理方法是什么?

    1 回复  |  直到 15 年前
        1
  •  1
  •   Joe Mastey    15 年前

    你试过检查吗 pageClass 在这个过程的早期,因为它似乎是必要的,甚至要把错误页拿出来?如果它不存在,并且如果你不想写404页而不写任何对象(例如HTML),那么在不存在该类的地方进行轰炸似乎是一条很好的途径。

    希望有帮助。

    谢谢, 乔