2011-11-06 118 views
2

我想重新定義Zend(RESTful)中幾個控制器的異常處理程序。如何在Zend中正確設置異常處理程序?

這是我的一段代碼:

abstract class RestController extends Zend_Rest_Controller 
{ 
    public function init() 
    { 
     set_exception_handler(array($this, 'fault')); 
    } 

    public function fault($exception = null, $code = null) 
    { 
     echo $exception->getMessage(); 
    } 
} 

但由於某些原因的Zend使用默認的模板/錯誤處理和我fault功能didnt執行。 順便說一句,我正在使用module架構。該控制器來自rest模塊.. Zend的默認錯誤處理程序來自default模塊。

回答

4

這是一個有趣的問題。我現在還不完全確定,所以我要研究這一點,看看我想出了什麼。現在有一些解決方案也不是太貧民窟。一種方法是創建一個抽象控制器,從中擴展您的休息模塊中的所有控制器。

abstract class RestAbstractController extends Zend_Rest_Controller 
{ 
    final public function __call($methodName, $args) 
    { 
     throw new MyRestException("Method {$methodName} doesn't exist", 500); 
    } 
} 

// the extends part here is optional 
class MyRestException extends Zend_Rest_Exception 
{ 
    public function fault($exception = null, $code = null) 
    { 
     echo $exception->getMessage() . ' ' . __CLASS__; 
     exit; 
    } 
} 

class RestController extends RestAbstractController 
{ 
    // method list 
} 

另外,我發現這個有趣的文章:http://zend-framework-community.634137.n4.nabble.com/Dealing-with-uncatched-exceptions-and-using-set-exception-handler-in-Zend-Framework-td1566606.html

編輯:

某處在引導文件,你需要補充一點:

$this->_front->throwExceptions(true); 
$ex = new MyRestException(); 
set_exception_handler(array($ex, 'fault')); 

第一行應該有有效地關閉Zend的異常處理,唯一缺少的是控制結構,以確定當前請求是否適用於您的REST服務。 注意這個必須在Bootstrap.php文件中的原因是你對init()函數中的set_exception_handler()的調用從未達到過,因爲Zend Framework首先拋出了異常。將其放置在引導文件中會對此進行反駁。

+0

它只適用於錯過的方法,但用戶生成的異常和mysql異常不會被捕獲。應該有另一種方式.. –

+0

好吧。以及檢查我的編輯。我認爲這應該是你的解決方案! –

+0

謝謝。我也想過bootstrap,但是在那種情況下,我錯過了OOP和控制器的所有優點。 –

-1

終於解決了這個問題由我自己:)

Zend documentation

對於Zend_Controller_Front :: throwExceptions()

通過傳遞一個true值這個方法,你可以告訴前 控制器,而不是聚合在響應 對象或使用錯誤處理程序插件異常,你寧願處理它們 自己

所以,正確的解決辦法是這樣的:

abstract class RestController extends Zend_Rest_Controller 
{ 
    public function init() 
    { 
     $front = Zend_Controller_Front::getInstance(); 
     $front->throwExceptions(true); 

     set_exception_handler(array($this, 'fault')); 
    } 

    public function fault($exception = null, $code = null) 
    { 
     echo $exception->getMessage(); 
    } 
} 

我們只需要添加

$front = Zend_Controller_Front::getInstance(); 
$front->throwExceptions(true); 

set_exception_handler之前,使其工作。