2016-10-03 65 views
0

我有點卡在我目前正在開發的web應用程序中。我決定將與try/catch-blocks一起使用Exceptions更加刻意。PHP5.6服務器上沒有捕獲到的異常

儘管如此,我在本地使用PHP7開發了,當我剛將應用上傳到PHP5服務器時,所有這些異常都不再受到影響。相反,腳本執行會因致命錯誤而停止。我已經閱讀了一些關於使用PHP7的例外的重大更改,但是我發現的所有信息都非常模糊。

腳本停止並不是一個問題,但捕獲和「修改」錯誤在這種情況下非常重要,因爲腳本是由AJAX調用運行的,並且必須返回JSON格式的錯誤消息。

主文件:

try { 

    if (!$this->validateNonce($this->postParams['upload-nonce'])) 
    throw new Exception('Upload failed because nonce could not be verified.'); 

    new FloImage(
     $this->postParams['basename'], 
     true, 
     $this->fileParams['uploadfile'] 
    ); 

} catch (Throwable $e) { 

    echo json_encode(array('error' => $e->getMessage())); 
    die(); 

} 

FloImage()檢查的一些信息(名稱,文件大小等),並在錯誤的情況下拋出一個異常這樣:

throw new Exception(_('My error message.')); 

幫助關於如何使try-catch-block與PHP5一起工作將不勝感激!預先感謝...

+0

你得到的致命錯誤是什麼? –

+0

我總是得到我正在拋出的錯誤。致命錯誤:我的消息。 –

+0

'Throwable'是PHP7中的基礎接口 - > [docs](http://php.net/manual/en/class.throwable.php)我認爲你不能捕捉它,因爲'Exception'不能實現PHP5中的界面 –

回答

1

Throwable是PHP7中引入的一個接口。從manual它指出:

Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7, including Error and Exception.

因此,如果你想使用PHP5你的代碼,你必須抓住Exception本身。即

try { 
    throw new Exception('Some exception'); 
} 
catch (\Exception $e) // use the backslash to comply with namespaces 
{ 
    echo($e->getMessage()); 
    die(); 
} 

只要拋出的異常來源於Exception,這將工作。即

class SpecialException extends Exception {} 

try { 
    throw new SpecialException('Some exception'); 
} 
catch (\Exception $e) // use the backslash to comply with namespaces 
{ 
    echo($e->getMessage()); 
    die(); 
} 
0

可能是你正在尋找這是用來編寫用戶定義的錯誤處理函數。因此,在腳本執行的頂部設置錯誤處理程序。

不要忘記在腳本的末尾放置restore_error_handler()以恢復以前的錯誤處理函數。

您可以在set_error_handler()函數中相應地恢復您的腳本。

+0

我想使用try/catch,而不是錯誤處理程序。無論如何,感謝您的建議! –