2011-02-11 64 views
1

我有一個自定義異常類與show()方法,以美麗的方式顯示異常。
在某些致命錯誤中,我遺留了未捕獲的異常,所以程序中間存在,但我希望這些異常可以用show方法顯示。
可以這樣做嗎?發送未捕獲的異常到一個特定的方法

class MyException extends Exception 
{ 
    public $e; 
    public function _contruct($message, $code = 0) 
    { 
     parent::_construct($message, $code); 
    } 

    public function show() 
    { 
     if(!defined('DEBUG')) define('DEBUG', FALSE); 
     p("Error: " . $this->getMessage()); 
     if(DEBUG) 
     { 
      p('Stack trace'); 
      p($this->getFile() . ' (' . $this->getLine() . ')'); 
      pre(get_dump($this->getTraceAsString())); 
     } 
    } 
} 

解決方案

class MyException extends Exception 
{ 
    public $e; 
    public function _contruct($message, $code = 0) 
    { 
     parent::_construct($message, $code); 
    } 

    public function show() 
    { 
     MyException::realShow($this); 
    } 

    static function realShow($e) 
    { 
     if(!defined('DEBUG')) define('DEBUG', FALSE); 
     p("Error: " . $e->getMessage()); 
     if(DEBUG) 
     { 
      p('Stack trace'); 
      p($e->getFile() . ' (' . $e->getLine() . ')'); 
      pre(get_dump($e->getTraceAsString())); 
     } 
    } 
} 

如果有人有更好的辦法,我是所有人的目光。

function exception_handler($ex) { 
    //$ex will be the thrown Exception object 
} 

set_exception_handler('exception_handler'); 

從文檔:

回答

1

當然,你可以使用set_exception_handler功能設置未捕獲的異常處理函數

設置默認的異常處理程序,如果一個異常沒有在try抓/ catch塊。調用exception_handler後執行將停止

此外,您不需要重寫構造函數,如果未覆蓋父類的構造函數,它將自動調用。

+0

是這樣的? set_exception_handler( 'MyException ::顯示'); – 2011-02-11 05:47:19

-1

您不應該在PHP中使用異常系統。

如文檔中表示:

PHP的例外製度使每個對象的某些費用他們甚至拋出了。這需要細緻的內存處理,並且僅建議用於系統嚴重性異常(您或用戶無法控制)。對於更常見的情況,最好在定製的非Exception對象上使用trigger_error。