2014-01-31 25 views
0

我使用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); 
    } 
+0

我建議你把'嘗試/ catch'在你發送你的要求的切入點。因此,在這種情況下,您可以在代碼中引發異常,並將它們捕獲到一個地方並以您想要的方式記錄它們。 –

回答

1

所以我會做這樣

try{ 
    if ((int)method_exists($controller, $action)) { 
     throw new Exception("FATAL ERROR: 101.".$controller."-".$action); 
    } 
    $ResultArray = call_user_func_array(array($dispatch,$action),$queryString); 
    return $ResultArray; 
} catch(Exception $e){ 
    exit('FATAL ERROR: ' .$e->getMessage() .' <br />\n"'); 
} 
+0

謝謝,這對我工作! –

+1

如果能幫助您,請您將我的問題標記爲已接受? –