异常捕获和CallHook

时间:2014-01-31 13:58:00

标签: php exception-handling autoload

我正在使用callhook在我的MVC框架中执行我的类和方法。不,我想用PHP异常函数添加错误处理。我只是想知道它在哪里是执行catch命令的最佳位置。请求(当然)可以导致多个类的执行。在整个系统中都有例外。 (例子如下所述)。

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);
    }

1 个答案:

答案 0 :(得分: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"');
}