【发布时间】:2010-05-13 12:08:47
【问题描述】:
假设使用 Exception 类的自定义扩展来处理自定义异常, 比如这样:
$testObject = new testClass();
还有这样的自动加载:
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>');
}
文件 testClass.php 不存在,因此调用 loadException 并显示以下消息: 文件 testClass.php 丢失。 (以及所有其他细节......行号等)
一切都很好,直到我决定隐藏所有错误并改为显示 404 页面(或 500 页面......),所以我很自然地想添加一个 loadErrorPage 函数。
class loadException {
...
function loadErrorPage($code){
$page = new pageClass();
echo $page->showPage($code);
}
}
...
try {
$testObject = new testClass();
}catch(loadException $e){
$e->loadErrorPage(500);
}
但这有一个明显的问题,如果缺少 testClass.php 和 pageClass.php 文件,则会显示致命错误而不是首选 404 页面。
我很困惑:S 如何在异常句柄中优雅地处理这个异常?
【问题讨论】: