2012-06-12 31 views
1

我對PHP相當陌生並且設置了自定義錯誤處理程序,但我有一些代碼在CI之外正常工作,但我無法解決如何集成這成一個CI控制器。我得到一個錯誤「消息:未定義的屬性:錯誤:: $ my_error_handler」如何在Codeigniter中設置自定義錯誤處理程序以發送電子郵件錯誤

我的控制器是:

<?php 
class Errors extends CI_Controller { 


    public function __construct() 
    { 
     parent::__construct(); 

    } 

    function my_error_handler($number, $message, $file, $line, $vars) 
    { 
     $email = " 
      <p>An error ($number) occurred on line 
      <strong>$line</strong> and in the <strong>file: $file.</strong> 
      <p> $message </p>"; 

     $email .= "<pre>" . print_r($vars, 1) . "</pre>"; 

     $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 

     // Email the error to someone... 
     error_log($email, 1, '[email protected]', $headers); 

     // Make sure that you decide how to respond to errors (on the user's side) 
     // Either echo an error message, or kill the entire project. Up to you... 
     // The code below ensures that we only "die" if the error was more than 
     // just a NOTICE. 
     if (($number !== E_NOTICE) && ($number < 2048)) { 
      die("There was an error. Please try again later."); 
     } 
    } 


    function test() 
    { 
     // We should use our custom function to handle errors. 
     set_error_handler($this->my_error_handler); 

     // Trigger an error... (var doesn't exist) 
     echo $somevarthatdoesnotexist; 

    } 

} 
?> 

如果有更好的方式使用CI請讓我知道電子郵件的錯誤消息。

+0

做到這一點:http://stackoverflow.com/questions/6403571/codeigniter-email-error-handling –

回答

8

我不要一個類的方法認爲擴展CI_Controller是解決這個問題的正確方法。相反,你應該擴展CI_Logs發送一封電子郵件,每當記錄一個錯誤:

class MY_Log extends CI_Log { 

    function MY_Log(){ 

     parent::__construct(); 

    } 

    function write_log($level = 'error', $msg, $php_error = FALSE){ 

     $result = parent::write_log($level, $msg, $php_error); 

     if ($result == TRUE && strtoupper($level) == 'ERROR') { 

      $message = "An error occurred: \n\n"; 
      $message .= $level.' - '.date($this->_date_fmt). ' --> '.$msg."\n"; 

      $this->CI =& get_instance(); 
      $to = $this->CI->config->item('email_admin_address'); 
      $from_name = $this->CI->config->item('email_general_name'); 
      $from_address = $this->CI->config->item('email_general_address'); 

      $subject = 'An error has occured'; 
      $headers = "From: $from_name <$from_address>" . "\r\n"; 
      $headers .= 'Content-type: text/plain; charset=utf-8\r\n'; 

      mail($to, $subject, $message, $headers); 

     } 

     return $result; 

    } 

}

保存這類應用\庫\ MY_Logs.php不要忘記啓用錯誤日誌記錄在你的config.php:$config['log_threshold'] = 1;

榮譽WPStorm,誰想出了這個想法第一。

0

如果您擴展核心例外類,您將能夠在其中添加所需的功能。

Codeigniter forum post on extending that class

希望這有助於

+0

嗨邁克爾。是的,這已經指出了我發送電子郵件發送所有錯誤的正確方向,但是如果在控制器的特定方法中發生錯誤,我還需要能夠進行數據庫更新。我想我可能不需要調整例外類來做到這一點。你有什麼建議? –

2

我已經找到了解決辦法。

set_error_handler(array(&$this, 'my_error_handler')); 

既然你要告訴錯誤處理,這是你要調用(預期的set_error_handler(array(&$this, ‘method’))意思),而不僅僅是一個功能(的set_error_handler(‘function’)本意)