2014-10-29 66 views
0

我正試圖在庫中捕獲Laravel異常。無法捕獲Laravel 4異常

namespace Marsvin\Output\JoomlaZoo; 

class Compiler 
{ 

    protected function compileItem($itemId, $item) 
    { 
     $boom = explode('_', $itemId); 
     $boom[0][0] = strtoupper($boom[0][0]); 
     $className = __NAMESPACE__."\\Compiler\\".$boom[0]; 

     try { 
      $class = new $className(); // <-- This is line 38 
     } catch(\Symfony\Component\Debug\Exception\FatalErrorException $e) { 
      throw new \Exception('I\'m not being thrown!'); 
     } 
    } 
} 

這一點,除了我得到:

file: "C:\MAMP\htdocs\name\app\libraries\WebName\Output\JoomlaZoo\Compiler.php" 
line: 38 
message: "Class 'Marsvin\Output\JoomlaZoo\Compiler\Deas' not found" 
type: "Symfony\Component\Debug\Exception\FatalErrorException" 

類的名稱是自願錯誤。

編輯1:

我注意到,如果我扔try語句中的異常,我可以捕獲該異常:

try { 
    throw new \Exception('I\'d like to be thrown!'); 
} catch(\Exception $e) { 
    throw new \Exception('I\'m overriding the previous exception!'); // This is being thrown 
} 
+1

快速檢查:做一個'抓(\例外$ E){拋出新的\異常(」拋出的異常是一個「.get_class($ e);}',所以你知道它是否真的是你正在試圖捕獲的正確的一個 – Wrikken 2014-10-29 16:22:48

+0

你也有一個語法錯誤'throw new \ Exception('我不是被拋出!');'字符串中的引號應該被轉義或者使用雙引號,但這可能只是這個例子的一個問題 – Bogdan 2014-10-29 16:24:43

+0

@Wrikken我嘗試過了,但是我仍然得到了Symphony的'FatalErrorException'。添加輸出到問題 – siannone 2014-10-29 16:26:52

回答

1

的問題是,你要趕上FatalErrorException在你的班上,但拉拉維爾不會讓一個致命的錯誤回到那裏;它立即終止。如果你試圖捕捉一種不同的異常,你的代碼就可以正常工作。

您可以通過app/start/global.php中的App::fatal method捕獲並處理致命錯誤,但這不會幫助您處理庫中的異常,也無法處理任何特定的異常。更好的選擇是觸發一個「可捕獲」的異常(例如Illuminate),或者根據您正在嘗試檢查的條件拋出一個自定義異常。

在你的情況,如果你的目標是應對不確定的類,這裏是我建議:

try { 
    $className = 'BadClass'; 
    if (!class_exists($className)) { 
     throw new \Exception('The class '.$className.' does not exist.'); 
    } 
    // everything was A-OK... 
    $class = new $className(); 
} catch(Exception $e) { 
    // handle the error, and/or throw different exception 
    throw new \Exception($e->getMessage()); 
} 
+0

謝謝,這解決了我的問題。 – siannone 2014-10-30 08:32:05