3.PHP Custom Error Handler

Source: Internet
Author: User
Tags vars

1. using Set_error_handler to customize the error handling function description

  • 1. Creating the error handling function
  • 2. Set different levels of call functions
  • 3.set_error_handler function specifies takeover error handling
  • Set_error_handler description

    Mixed Set_error_handler (callable $error _handler [, int $error _types = E_all | E_STRICT]) Set a user's function (Error_Handler) to handle errors that occur in the script. This function can handle a running error in your own way, for example, when a critical error occurs in the application, or an error is triggered under certain conditions (using Trigger_error ()), you need to clean up the data/file. It is important to remember that the error type specified in the Error_types bypasses the PHP standard error handler unless the callback function returns FALSE. The error_reporting () setting will not function and your error handler will continue to be called?? However, you can still get the current value of the error_reporting and do the appropriate processing. It is important to note that when an error occurs with a statement with the @ error-control operator prefix, this value is 0. Also note that you are responsible for using die () when needed. If the error handler returns, the script will continue to execute the following line where the error occurred. The following level of errors cannot be handled by user-defined functions: E_error, E_parse, E_core_error, e_core_warning, E_compile_error, e_compile_warning, and in call set_ Most e_strict generated in the file where the Error_Handler () function is located. If the error occurs before the script executes (such as when a file is uploaded), the custom error handler will not be called because it is not yet registered at that time. Parameter error_handler the user's function needs to accept two parameters: the error code and the string that describes the error. It is also possible to provide three optional parameters: the file name where the error occurred, the line number where the error occurred, and the context in which the error occurred (an array pointing to the active symbol table when the error occurred). The function can be represented as: handler (int $errno, String $errstr [, String $errfile [, int $errline [, array $errcontext]]) errno first argument err No, contains the level of error, is an integer. Errstr the second parameter, ERRSTR, contains the wrong information, which is a string. Errfile The third parameter is optional, ErrfiLe, which contains the name of the file where the error occurred, is a string. Errline The fourth parameter is an optional, errline, containing the line number of the error that occurred, is an integer. Errcontext Fifth optional parameter, Errcontext, is an array that points to the active symbol table when an error occurs. That is, Errcontext contains an array of all the variables in the scope at which the error is triggered. The user's error handler should not modify the error context. If the function returns FALSE, the standard error-handling handler will continue to be called. Error_types like the Error_reporting INI setting that controls the display of errors, this parameter can be used to mask the triggering of the Error_Handler. Without the mask, regardless of how error_reporting is set, Error_Handler is called every time the error occurs.

    2. Use of Set_error_handler

    Header (' content-type:text/html; Charset=utf-8 ');//Turn on all error reports error_reporting ( -1); function Customerror ($errno, $ ErrMsg, $errfile, $errline) {if (! (    Error_reporting () & $errno)) {//This error code was not included in Error_reporting return; } switch ($errno) {case E_user_error:echo "My ERROR[$errno] $errmsg
    ". Php_eol; echo "Fatal error on line $errline in file $errfile"; echo ", PHP". Php_version. " (" . Php_os. ")
    ". Php_eol; echo "Aborting ...
    \ n "; Exit (1); Break Case E_user_warning:echo "My WARNING[$errno] $errmsg
    ". Php_eol; Break Case E_user_notice:echo "My NOTICE[$errno] $errmsg
    ". Php_eol; Break Default:echo "Unknown error type: [$errno] $errmsg
    ". Php_eol; Break }/* Don ' t execute PHP Internal Error handler */return TRUE;} Set_error_handler (' customerror '); echo $test; Settype ($var, ' King ');//test (); Trigger_error (' Wrong! ', E_user_error, echo ';//Recovery Error takeover restore_error_handler (); Echo $king; Echo '; Set_error_handler (' Customerror ', E_all &~e_notice), Echo ', Settype ($var, ' King '), Echo ' Continue ...... ';

    3. Custom Error Handling classes

    /** * Custom error handling class */class MyErrorHandler {public $msg = ';    public $filename = ';    Public $line = 0;    Public $vars =array ();    protected $_noticelog = '/tmp/php_error.log ';        function __construct ($msg, $filename, $line, $vars) {$this->msg= $msg;        $this->filename= $filename;        $this->line= $line;    $this->vars= $vars; }/** * [deal custom error handling request] * @param [int] $errno [ERROR number] * @param [string] $errmsg [ERROR description] * @param [string] $errfile [Error file ] * @param [int] $errline [line number of ERROR] * @param [array] $vars [array of all variables within scope of the error trigger] * @return [BOOL] */public static function        Deal ($errno, $errmsg, $errfile, $errline, $vars) {$self = new self ($errmsg, $errfile, $errline, $vars);                Switch ($errno) {//Fatal-level error message to administrator case E_user_error:return $self->dealerror ();            Break                Case E_user_warning:case E_warning:return $self->dealwarning ();          Break  Case E_user_notice:case E_notice:return $self->dealnotice ();            Break                Default://The error mechanism given to PHP itself to handle return false;        Break        }} Public Function Get_debug_print_backtrace ($traces _to_ignore = 1) {$traces = Debug_backtrace ();        $ret = Array ();            foreach ($traces as $i = + $call) {if ($i < $traces _to_ignore) {continue;            } $object = ';                if (Isset ($call [' class])) {$object = $call [' class ']. $call [' type ']; if (Is_array ($call [' args '])) {foreach ($call [' args '] as & $arg) {$this                    Get_arg ($arg); }}} $ret [] = ' # '. Str_pad ($i-$traces _to_ignore, 3, '). $objec T. $call [' function ']. ' ('. Implode (', ', $call [' args ']) Called at ['. $call [' file ']. ': '. $call[' line '].    } return implode ("\ n", $ret);            The Public Function Get_arg (& $arg) {if (Is_object ($arg)) {$arr = (array) $arg;            $args = Array ();    foreach ($arr as $key = + $value) {if (Strpos ($key, Chr (0))!== false) {$key = ';            Private variable found} $args [] = ' ['. $key. '] = '. Get_arg ($value); } $arg = Get_class ($arg).        ' Object ('. Implode (', ', $args). ') '; }}/** * [Dealerror Handling Error level ERROR] * @return [type] [description] * * Public Function Dealerror () {$backtrace =        $this->get_debug_print_backtrace (); Echo $backtrace;        Exit $ERRORMSG =<<
      filename} generated the wrong message: {$this->msg} generated the wrong line number: {$this-&GT;LINE} tracking information: {$backtrace} \ n EOF;        Error_log ($ERRORMSG, 1, ' 732578448@qq.com ');    Exit (1); }/** * [dealwarning Handling Warning Level ERROR] * @return [BOOL] */Public Function dealwarning () {$ERRORMSG =<<
        filename} generates a warning message: {$this->msg} The line number that generated the warning: {$this->line} \ n EOF;    Error_log ($ERRORMSG, 1, ' 732578448@qq.com '); }/** * [DEALNOTICE Processing notification level ERROR] * @return BOOL */Public Function Dealnotice () {$datetime = date (' y-m-d h:i:s ')        , time ());        $ERRORMSG =<< 
         filename} generates notification information: {$this->msg} The line number that generated the notification: {$this->line} time to generate notification: {$datetime} \ n EOF;    Return Error_log ($ERRORMSG, 3, $this->_noticelog); }}error_reporting ( -1); Set_error_handler (Array (' MyErrorHandler ', ' deal ')); Ini_set (' Display_errors ', 0); Echo $var;
     Trigger_error (' zhiming ', e_user_error); Trigger_error (' zhiming ', e_user_warning); 

    Use of the 4.register_shutdown_function function

    2. Use

    1. With the Register_shutdown_function function, let's set up another function that can be called when execution is closed.
    2. Our function will be called when the execution of our script completes or the Accidental death causes PHP execution to close.

    2. Usage Scenarios

    1. Page forced to be stopped
    2. Program code terminated unexpectedly or timed out

    3. Attention Points

    1. Cannot have Die () exit () termination function before register_shutdown_function

    Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

  • 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.