我使用callhook在我的MVC框架中執行我的類和方法。不,我想用PHP異常函數添加如此的錯誤處理。我只是想知道它在哪裏是執行catch命令的最佳位置。一個請求可以(當然)導致執行多個類。整個系統例外。 (例子在下面提到)。例外Catch和CallHook
function callHook() {
global $urlArray;
//DEFINE CONTROLLERS
if (strlen(strstr($urlArray[0],'popup_'))>0)
{
$controller = substr($urlArray[0], 6);
}
else
{
$controller = $urlArray[0];
}
$queryString[] = $urlArray[1];
$URLaction = $urlArray[2];
if(!isset($controller) && empty($controller)){ $controller = 'home';}
if(!isset($URLaction) || empty($URLaction)){$action = 'view';}else{$action = $URLaction;}
$controllerName = str_replace('-','', $controller);
$controller = ucwords($controller);
$model = rtrim($controller, 's');
$controller .= 'Controller';
$dispatch = new $controller($model,$controllerName,$action);
if ((int)method_exists($controller, $action)) {
$ResultArray = call_user_func_array(array($dispatch,$action),$queryString);
return $ResultArray;
} else {
exit("FATAL ERROR: 101.".$controller."-".$action);
}
}
示例類:
public function CheckCarExistance(){
if(!is_object($this-> carId)){throw new Exception("carId is missing!");}
$CountCars = new modelmysql();
$CountCars->connect();
$CountCars->count('system_cars', "carId = '".mysql_real_escape_string($this-> carId)."'");
$this->results = $CountCars ->getResult();
}
要顯示所有的異常這將是放置的try/catch中調用掛鉤或只是在每一個類/方法是一個好主意?
Callhook
if ((int)method_exists($controller, $action)) {
try{
$ResultArray = call_user_func_array(array($dispatch,$action),$queryString);
return $ResultArray;
}
catch(Exception $e){
echo 'Error Found message: ' .$e->getMessage() .' <br />\n";';
}
} else {
exit("FATAL ERROR: 101.".$controller."-".$action);
}
我建議你把'嘗試/ catch'在你發送你的要求的切入點。因此,在這種情況下,您可以在代碼中引發異常,並將它們捕獲到一個地方並以您想要的方式記錄它們。 –