我需要說明我回答這個問題之前,該程序的程序員將着眼於這一點,並認爲這是愚蠢的:),但我可以忍受的,這是假設與HTML模板的output_buffer清洗後輸出一個面向對象的應用程序。
我總是在一次調用中創建一個try/catch塊,其中包含大部分代碼,通常在開始需要其他文件以及開發時啓動output_buffer的時候。
ob_start();
try {
switch($appPage) {
case('work'):
require_once('im_bored_at_work.php');
break;
case('home'):
require_once('im_a_little_less_bored_at_home.php');
break;
default:
require_once('on_the_fence.php');
}
} catch (Exception $e) {
// Handle exception caught and apply formatting
}
$devOut = ob_get_contents();
ob_end_flush();
舉一個例子,我將如何處理你需要捕捉一個自定義類的多個異常
class CustomExceptionHandler extends Exception {
private $msg;
private $code;
private $otherVars;
public function __construct($msg,$code=0,$otherDebugVar=null){
$this->msg = $msg != null ? $msg : "An unknown exception was thrown";
$this->code = $code;
$this->otherVars = $otherDebugVar;
parent::__construct($msg,$code);
}
public function getOtherVars() {
return $this->otherVars;
}
}
的想法是隻保留異常對象中的自定義信息,當你將try/catch塊末尾的異常重新拋出,作爲包含格式化定製消息的標準異常,現在應該無關緊要地知道哪個異常處理程序獲取了原始異常,因爲您需要的所有信息都會到達下游併成爲抓住原來的try/catch塊。
class BasicTemplate {
private $template;
private $path;
private $contents;
public function __construct($template, $path) {
$this->template = $template;
$this->path = $path;
$this->buildTemplate();
}
private function buildTemplate() {
if ($contents = @file_get_contents($this->path . $this->template)) {
$this->contents = $contents;
} else {
$e = new CustomExceptionHandler("Message",2,$this->path . $this->template);
// Do whatever else you want to do with custom exception handling class
throw $e;
}
}
}
現在,你需要抓住你的異常,並重新拋出:
try {
$html = new BasicTemplate($temp,$path);
} catch {CustomExceptionHandler $e) {
throw new Exception("Message: {$e->getMessage()} Other Info: {$e->getOtherVars()}",$e->getCode());
}
這無論如何是粗糙的想法,希望它幫助。
我試圖通過你的邏輯思考這裏,它似乎相當複雜(異常處理+額外的代碼+)。我傾向於爲每個類(除了總決賽)創建自定義異常處理程序,當我捕捉到異常時,將它們作爲標準異常重新拋出,並附上我的客戶錯誤消息,錯誤代碼和自定義處理程序創建的回溯。通過這種方式,我可以獲取所有異常,並且如果需要通過調用擴展異常處理程序中的方法深入到我的代碼中。 – 2012-03-10 01:00:46
@DavidBarker,其中一個異常是通過PDO拋出的PDOException。我不能用try-catch塊來包裝我所有的代碼或所有的PDO函數,所以我認爲只要抓住它並處理它就更容易。不是嗎? – Shoe 2012-03-10 02:30:10
我不太瞭解PHP,但似乎重載的「渲染」方法會更方便。當你發現異常時,你知道它的類型。如果PHP不支持重載,則可以創建renderEx1,renderEx2等。 – dsboger 2012-03-11 20:45:27