2015-06-19 70 views
0

我對許多try/catch塊使用了PHP異常,並且所有工作都正常,除了一個特定的片段。PHP異常處理無法正常工作

見下面的碼:

Controller.class

<?php 
namespace Controller; 

use Business\Exceptions\AppException; 
use Business\OTA\Responses\Erros\RS_ERROR; 
use Utils\Merge; 

class Controller{ 
    //other methods 

    public main(){ 
     //do stuff 
     $resp = $this->merge($con) 
    } 

    private function merge($con) 
    { 
     try { 
      $merge = new Merge($this->record, $con); 
      $merge->sortResponses(); 
      return $merge->searchResponse; 
     } catch (AppException $ex){ 
      $response = new RS_ERROR($this->client); 
      echo ($response); 
     } 
    } 
} 

Merge.class(簡化的)

<?php 
namespace Utils; 

use Business\Exceptions\AppException; 
use Exception; 

class Merge 
{ 

    public $responses;   
    public $conectors; 
    public $searchResponse; 

    /** 
    * Method __construct 
    * @param array $conectorResponses 
    * @param $conectors 
    * @throws \Business\Exceptions\AppException 
    */ 
    public function __construct(array $conectorResponses, $conectors) 
    { 
     $this->responses = $conectorResponses; 
     $this->conectors = $conectors; 
     $this->searchResponse = array(); 
     if (empty($this->responses)) { 
      $ex = new AppException("Search Not found", '11'); 
      throw $ex; 
     } 
    } 

當我運行代碼和呼叫合併構造,即使$this->responses爲空時,Exception也會拋出,但它不是catche在控制器d,我看到通知

PHP的通知:試圖讓非對象的財產/var/www/ws-test/app/Controller/Controller.class.php上線96

指的是線路return $merge->searchResponse;

當我調試的代碼,我可以使用throw $ex斷點,但這不是逮住。 我做錯了什麼?爲什麼這個例外被忽略?

我在這裏看到一些類似的問題,但任何描述相同的問題。

+0

如果添加'趕上(例外$前){}''的捕撈(AppException $ EX)後{'這是否捕獲此異常? – RiggsFolly

+0

@RiggsFolly。我還沒有嘗試過(mea culpa),但我現在更改爲'Exception',然後錯誤被正確捕捉,儘管我不明白爲什麼 – James

+1

因爲該異常是由系統生成的,而不是手動生成的AppException。我猜想構造器中還有其他問題出錯了,因此該對象並沒有真正創建 – RiggsFolly

回答

1

自己是不是在你的代碼正確:

$this->searchResponse = array(); 

則返回一個空數組:

return $merge->searchResponse; 

也許你的意思是:

return $merge->responses; 

要確保你捕捉到所有的異常,趕上你所有的習慣第一個那麼最後一個catch塊添加Exception

try { 
    //code 
} catch (AppException $ex){ 
    $response = new RS_ERROR($this->client); 
    echo ($response); 
}catch (Exception $e){ 
    var_dump($e); 
}