开发者

php: handling exceptions within exception handlers?

开发者 https://www.devze.com 2022-12-29 23:36 出处:网络
Let\'s say were using custom extensions of the Exception class to handle custom exceptions, like this for example:

Let's say were using custom extensions of the Exception class to handle custom exceptions, like this for example:

$testObject = new testClass();

and a autoload like this:

function __autoload($class_name) {
    $file = $class_name.'.php';
    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");
    }
    return true;
}

try {
    $testObject = new testClass();
}catch(loadException $e){
    exit('<pre>'.$e.'</pre>');
}

the file testClass.php does not exist, so a loadException 开发者_运维知识库is called with the message: File testClass.php is missing. (and all the other details...line number etc)

all was fine, until i decided to hide all the errors and instead display a 404 page (or a 500 page...), so naturally i thought to add a loadErrorPage function.

class loadException {

...

    function loadErrorPage($code){
        $page = new pageClass();
        echo $page->showPage($code);
    }
}

...

try {
    $testObject = new testClass();
}catch(loadException $e){
    $e->loadErrorPage(500);
}

but this has the obvious problem that if the testClass.php AND pageClass.php files are missing, then a fatal error is shown instead of the preferred 404 page.

I'm confused :S How do I elegantly handle this exception within a exception handle?


If class pageClass does not exist and cannot be loaded by your autloader $page = new pageClass(); in your method loadErrorPage() will cause another exception. You'd have to catch this exception and then do something without that class.

function loadErrorPage($code){
  try {
    $page = new pageClass();
    echo $page->showPage($code);
  }
  catch(Exception $e) {
    // header(...500);
    echo 'fatal error: ', $code;
  }
}


Well, you could always just not delete pageClass.php...

I'm assuming that's just one file, shouldn't be too hard to make sure it doesn't disappear, in the same way you're making sure the file which has your __autoload function in it doesn't go anywhere.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号