簡體   English   中英

無法捕獲Laravel 4異常

[英]Cannot catch Laravel 4 exception

我正在嘗試在我的庫中捕獲Laravel異常。

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
}

問題是您試圖在類中捕獲FatalErrorException ,但是Laravel不會讓致命錯誤返回那里; 它立即終止。 如果您試圖捕獲另一種異常,則您的代碼將正常工作。

您可以使用app/start/global.phpApp::fatal方法捕獲並處理致命錯誤,但這不會幫助您從庫中處理異常或以任何特定方式處理該異常。 更好的選擇是觸發“可捕獲”異常(例如,來自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());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM