A very good display of PHP error, exception handling class _php tutorial

Source: Internet
Author: User
Tags php debug php error
One:


Second, the implementation of the Code

Copy the Code code as follows:

Custom Exception functions
Set_exception_handler (' handle_exception ');

Custom error functions
Set_error_handler (' Handle_error ');

/**
* Exception Handling
*
* @param mixed $exception Exception object
* @author blog.snsgou.com
*/
function Handle_exception ($exception) {
Error::exceptionerror ($exception);
}

/**
* Error Handling
*
* @param string $errNo error code
* @param string $ERRSTR error message
* @param string $errFile error file
* @param string $errLine error line
* @author blog.snsgou.com
*/
function Handle_error ($errNo, $errStr, $errFile, $errLine) {
if ($errNo) {
Error::systemerror ($errStr, False, True, false);
}
}

/**
* System error Handling
*
* @author blog.snsgou.com
*/
Class Error {

public static function Systemerror ($message, $show = True, $save = True, $halt = True) {

List ($showTrace, $logTrace) = self::d ebugbacktrace ();

if ($save) {
$messageSave = ". $message. '
PHP:'. $logTrace;
Self::writeerrorlog ($messageSave);
}

if ($show) {
Self::showerror (' System ', "

  • $message
  • ", $showTrace, 0);
    }

    if ($halt) {
    Exit ();
    } else {
    return $message;
    }
    }

    /**
    * Code Execution Process backtracking information
    *
    * @static
    * @access Public
    */
    public static function Debugbacktrace () {
    $skipFunc [] = ' error->debugbacktrace ';

    $show = $log = ";
    $debugBacktrace = Debug_backtrace ();
    Ksort ($debugBacktrace);
    foreach ($debugBacktrace as $k = = $error) {
    if (!isset ($error [' File '])} {
    Use the reflection API to get the number of files and rows where the method/function resides
    try {
    if (Isset ($error [' class ')]) {
    $reflection = new Reflectionmethod ($error [' class '], $error [' function ']);
    } else {
    $reflection = new Reflectionfunction ($error [' function ']);
    }
    $error [' file '] = $reflection->getfilename ();
    $error [' line '] = $reflection->getstartline ();
    } catch (Exception $e) {
    Continue
    }
    }

    $file = Str_replace (Site_path, "', $error [' file ']);
    $func = Isset ($error [' class '])? $error [' class ']: ';
    $func. = Isset ($error [' type '])? $error [' type ']: ';
    $func. = Isset ($error [' function '])? $error [' function ']: ';
    if (In_array ($func, $skipFunc)) {
    Break
    }
    $error [' line '] = sprintf ('%04d ', $error [' line ']);

    $show. = '

  • [Line: '. $error [' line ']. ']' . $file. ' ('. $func. ')
  • ';
    $log. =!empty ($log)? ', ': ';
    $log. = $file. ':' . $error [' line '];
    }
    Return Array ($show, $log);
    }

    /**
    * Exception Handling
    *
    * @static
    * @access Public
    * @param mixed $exception
    */
    public static function Exceptionerror ($exception) {
    if ($exception instanceof dbexception) {
    $type = ' db ';
    } else {
    $type = ' System ';
    }
    if ($type = = ' db ') {
    $ERRORMSG = ' ('. $exception->getcode (). ') ';
    $errorMsg. = Self::sqlclear ($exception->getmessage (), $exception->getdbconfig ());
    if ($exception->getsql ()) {
    $errorMsg. = ';
    $errorMsg. = Self::sqlclear ($exception->getsql (), $exception->getdbconfig ());
    $errorMsg. = ';
    }
    } else {
    $ERRORMSG = $exception->getmessage ();
    }
    $trace = $exception->gettrace ();
    Krsort ($trace);
    $trace [] = Array (' file ' = = $exception->getfile (), ' line ' = + $exception->getline (), ' function ' = ' break ') ;
    $PHPMSG = Array ();
    foreach ($trace as $error) {
    if (!empty ($error [' function ')]) {
    $fun = ";
    if (!empty ($error [' class ')]) {
    $fun. = $error [' class ']. $error [' type '];
    }
    $fun. = $error [' function ']. '(';
    if (!empty ($error [' args '])) {
    $mark = ";
    foreach ($error [' args '] as $arg) {
    $fun. = $mark;
    if (Is_array ($arg)) {
    $fun. = ' Array ';
    } elseif (Is_bool ($arg)) {
    $fun. = $arg? ' True ': ' false ';
    } elseif (Is_int ($arg)) {
    $fun. = (defined (' Site_debug ') && site_debug)? $arg: '%d ';
    } elseif (Is_float ($arg)) {
    $fun. = (defined (' Site_debug ') && site_debug)? $arg: '%f ';
    } else {
    $fun. = (defined (' Site_debug ') && site_debug)? '\'' . Htmlspecialchars (substr (Self::clear ($arg), 0, 10)). (strlen ($arg) > 10? ' ...' : '') . ' \ ': '%s ';
    }
    $mark = ', ';
    }
    }
    $fun. = ') ';
    $error [' function '] = $fun;
    }
    if (!isset ($error [' line ')]) {
    Continue
    }
    $PHPMSG [] = Array (' file ' = + str_replace (Array (site_path, ' \ \ '), Array (', '/'), $error [' file ']), ' line ' = = $error [' Line '], ' function ' = $error [' function ']);
    }
    Self::showerror ($type, $ERRORMSG, $PHPMSG);
    Exit ();
    }

    /**
    * Log error logs
    *
    * @static
    * @access Public
    * @param string $message
    */
    public static function Writeerrorlog ($message) {

    return false; Temporarily do not write

    $message = Self::clear ($message);
    $time = time ();
    $file = Log_path. '/' . Date (' Y.M.D '). ' _errorlog.php ';
    $hash = MD5 ($message);

    $userId = 0;
    $ip = Get_client_ip ();

    $user = 'User: userid= '. Intval ($userId). '; Ip= '. $ip. '; RIP: '. $_server[' REMOTE_ADDR '];
    $uri = ' Request: '. Htmlspecialchars (Self::clear ($_server[' Request_uri '));
    $message = " \t{$time}\t$message\t$hash\t$user $uri \ n";

    Determine if the $message has been recorded within the time interval $maxtime, there is no need to record
    if (Is_file ($file)) {
    $fp = @fopen ($file, ' RB ');
    $lastlen = 50000; Reads the last $lastlen length byte content
    $maxtime = 60 * 10; Time interval: 10 minutes
    $offset = FileSize ($file)-$lastlen;
    if ($offset > 0) {
    Fseek ($fp, $offset);
    }
    if ($data = Fread ($fp, $lastlen)) {
    $array = explode ("\ n", $data);
    if (Is_array ($array))
    foreach ($array as $key = = $val) {
    $row = explode ("\ t", $val);
    if ($row [0]! = " ) {
    Continue
    }
    if ($row [3] = = $hash && ($row [1] > $time-$maxtime)) {
    Return
    }
    }
    }
    }

    Error_log ($message, 3, $file);
    }

    /**
    * Clear Text part characters
    *
    * @param string $message
    */
    public static function Clear ($message) {
    return Str_replace (Array ("\ t", "\ r", "\ n"), "", $message);
    }

    /**
    * SQL statement character cleanup
    *
    * @static
    * @access Public
    * @param string $message
    * @param string $dbConfig
    */
    public static function Sqlclear ($message, $dbConfig) {
    $message = Self::clear ($message);
    if (! ( Defined (' Site_debug ') && Site_debug)) {
    $message = Str_replace ($dbConfig [' Database '], ' * * * ', $message);
    $message = Str_replace ($dbConfig [' prefix '], ' * * * ', $message);
    $message = Str_replace (C (' Db_prefix '), ' * * * ', $message);
    }
    $message = Htmlspecialchars ($message);
    return $message;
    }

    /**
    * Error displayed
    *
    * @static
    * @access Public
    * @param string $type error type Db,system
    * @param string $ERRORMSG
    * @param string $PHPMSG
    */
    public static function ShowError ($type, $errorMsg, $PHPMSG = ") {
    Global $_g;

    $ERRORMSG = Str_replace (Site_path, ", $ERRORMSG);
    Ob_end_clean ();
    $host = $_server[' http_host ');
    $title = $type = = ' db '? ' Database ': ' System ';
    Echo <<


    <title>$host-$title Error</title>






    $title Error


    $errorMsg
    EOT;
    if (!empty ($PHPMSG)) {
    Echo ';
    Echo '

    PHP Debug

    ';
    Echo '














    '; if (Is_array ($PHPMSG)) {echo ' '; foreach ($phpMsg as $k = + $msg) {$k + +; Echo ' '; Echo ' '; Echo ' '; Echo ' '; Echo ' '; Echo ' '; }} else {echo ' '; } Echo '
    No. File Line Code
    ' . $k. '' . $msg [' file ']. '' . $msg [' line ']. '' . $msg [' function ']. '
      ' . $PHPMSG. '
    ';
    }
    Echo <<


    EOT;
    Exit ();
    }
    }

    /**
    * DB Exception class
    *
    * @author blog.snsgou.com
    */
    Class Dbexception extends Exception {

    protected $sql;
    protected $dbConfig; Current Database configuration information

    Public function __construct ($message, $code = 0, $sql = ", $dbConfig = Array ()) {
    $this->sql = $sql;
    $this->dbconfig = $dbConfig;
    Parent::__construct ($message, $code);
    }

    Public Function GetSQL () {
    return $this->sql;
    }

    Public Function Getdbconfig () {
    return $this->dbconfig;
    }
    }

    http://www.bkjia.com/PHPjc/744334.html www.bkjia.com true http://www.bkjia.com/PHPjc/744334.html techarticle One,: Two, the implementation code copy code is as follows:? PHP//Custom exception function Set_exception_handler (' handle_exception ');//Custom error function Set_error_handler ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.