2011-01-19 131 views
10

我想在我的php應用程序中處理異常。php自定義異常處理

當我拋出一個異常時,我想傳遞一個標題在錯誤頁面中使用。

可有人請聯繫我一個很好的教程,或寫的異常處理實際上是如何工作的一個明確的解釋(例如,如何知道你正在處理ECT什麼樣的異常。

回答

29

官方文檔是一個很好的開始 - http://php.net/manual/en/language.exceptions.php

如果它只是一個你想捕捉的信息,你會在下面做;

try{ 
    throw new Exception("This is your error message"); 
}catch(Exception $e){ 
    print $e->getMessage(); 
} 

如果你想捕獲特定的錯誤,你可以使用:

try{ 
    throw new SQLException("SQL error message"); 
}catch(SQLException $e){ 
    print "SQL Error: ".$e->getMessage(); 
}catch(Exception $e){ 
    print "Error: ".$e->getMessage(); 
} 

爲了記錄 - 你需要定義SQLException。這是可以做到簡單,如:

class SQLException extends Exception{ 

} 

對於標題和消息,則應擴展Exception類:

class CustomException extends Exception{ 

    protected $title; 

    public function __construct($title, $message, $code = 0, Exception $previous = null) { 

     $this->title = $title; 

     parent::__construct($message, $code, $previous); 

    } 

    public function getTitle(){ 
     return $this->title; 
    } 

} 

你可以調用這個使用:

try{ 
    throw new CustomException("My Title", "My error message"); 
}catch(CustomException $e){ 
    print $e->getTitle()."<br />".$e->getMessage(); 
} 
+1

謝謝你,這個答案是真棒。記住這個例子,如果我想傳遞一個標題以及只是消息,但我會怎麼做呢? – Hailwood 2011-01-19 09:43:22

3

首先,我要推薦看看corresponding PHP manual page,這是一個很好的開始。另外,你可以看看Extending Exceptions頁面 - 有關於標準異常類的更多信息,以及自定義異常執行的例子

如果問題是,如果拋出特定類型的異常時如何執行某些特定操作,那麼您只需在catch語句中指定異常類型:

try { 
     //do some actions, which may throw exception 
    } catch (MyException $e) { 
     // Specific exception - do something with it 
     // (access specific fields, if necessary) 
    } catch (Exception $e) { 
     // General exception - log exception details 
     // and show user some general error message 
    } 
2

試試這個作爲你的PHP頁面上的第一件事。

它捕捉php錯誤和異常。

function php_error($input, $msg = '', $file = '', $line = '', $context = '') { 
    if (error_reporting() == 0) return; 

    if (is_object($input)) { 
     echo "<strong>PHP EXCEPTION: </strong>"; 
     h_print($input); 
     $title = 'PHP Exception'; 
     $error = 'Exception'; 
     $code = null; 
    } else { 
     if ($input == E_STRICT) return; 
     if ($input != E_ERROR) return; 
     $title = 'PHP Error'; 
     $error = $msg.' in <strong>'.$file.'</strong> on <strong>line '.$line.'</strong>.'; 
     $code = null; 
    } 

    debug($title, $error, $code); 

} 

set_error_handler('php_error'); 
set_exception_handler('php_error');