2015-04-28 35 views
1

我有一個包含異常的類,如果異常未在類之外捕獲,我想要一個默認異常。覆蓋PHP中的默認異常消息

下面是一些代碼:

<?php 


Class Test 
{ 
    public $file; 


    public function setFile($file) 
    { 
     $this->file = $file; 
    } 

    public function getFile() 
    { 
     return $this->file; 
    } 

    public function test() 
    { 
     try 
     { 

      return $this->getFile(); 

      if($this->getFile() == "test") 
      { 
       throw new TestException("The variable is test!"); 
      } 
     } 
     catch (TestException $e) 
     { 
      return "Default exception message: " . $e->getMessage(); 
     } 
    } 
} 

class TestException extends \Exception 
{ 

    public function __construct($message) 
    { 
     parent::__construct($message); 
    } 
} 

$t = new Test; 
$t->setFile('test'); 
try { 
    echo $t->test(); 
} 
catch(TestException $e) { 
    //this wont do anything 
    return "I want to overwrite exception here... " . $e->getMessage(); 
} 

此外,不使用與捕捉try塊將只是把一個未捕獲的異常錯誤。

那麼有沒有辦法來重寫處理?最明顯的方法是在類中拋出一個錯誤,刪除try塊,並在類外捕獲異常,但是我想知道是否有重寫的方法。

回答

1

如果你想要我認爲你想要的。一種解決方案是使用set_exception_handler:http://php.net/manual/en/function.set-exception-handler.php

這意味着您可以刪除try-catch塊,並且任何未捕獲的異常都會以您給set_exception_handler()的函數結束。

雖然沒有爲異常處理程序設定範圍,但是這將是應用程序範圍的行爲。

0

如果傳遞一些額外的參數,可以說函數不會捕獲Eexception。

public function test(is_throw_exception=False) 
    { 
     try 
     { 
      . . . 
     } 
     catch (TestException $e) 
     { 
      if is_throw_exception { 
       throw new TestException("The variable is test!"); 
      } 
      return "Default exception message: " . $e->getMessage(); 
     } 
    } 
相關問題