簡體   English   中英

在Zend Framework 1中無需使用try catch即可處理異常

[英]Handle exception without using try catch in Zend Framework 1

我有一個在Zend Framework 1中開發的項目。該項目已完成。

現在,當我測試整個網站時,某些頁面引發了異常。 其中之一如下:

消息“沒有類型為NULL的適配器”的異常'Zend_Paginator_Exception'

我已經在網上搜索並獲得了向其中添加try-catch的步驟。 但是,檢查所有代碼並重復此步驟將花費大量時間。

我可以編寫一個捕獲所有異常並對其進行處理的通用異常處理程序嗎?

Zend框架使用errorController自動處理異常。 您可以通過在配置文件中添加以下行來啟用它。

resources.frontController.throwExceptions = 0

如果要手動處理異常,則可以在下面的代碼中將其集中起來,而不是在整個代碼中編寫try / catch塊。

告訴Zend Framework不處理異常。 在您的application.ini中執行此操作

resources.frontController.throwExceptions = 1

在Bootstrap類中定義一個自定義方法來處理異常。

public function __handleExceptions(Exception $e){
        //render a view with a simple error message for the user
        //and send an email with the error to admin
    }

覆蓋Bootstrap類中的Zend_Application_Bootstrap_Bootstrap的_bootstrap()run()方法,如下所示。 這將捕獲在引導和請求分配過程中引發的所有異常,並調用您的自定義異常處理程序。

protected function _bootstrap($resource = null)
    {
        try {
            parent::_bootstrap($resource);
        } catch(Exception $e) {
            $this->__handleExecptions($e);
        }
    }

    public function run()
    {
        try {
            parent::run();
        } catch(Exception $e) {
            $this->__handleExecptions($e);
        }
    }

這將消除在多個位置編寫try / catch塊的需要。 希望這可以幫助。

如果您在index.php中有這一行

$application->bootstrap()->run();

你可以用try catch塊包裝它

try {
    $application->bootstrap()->run();
} catch (Exception $e) {
    //handle all exceptions here
}

當然,對於不同類型的異常,您也可以具有許多catch塊。

暫無
暫無

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

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