3.PHP Custom Error Handler

Source: Internet
Author: User
Tags vars

1. using the Set_error_handler custom 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--but you can still get the current value of error_reporting and do the appropriate processing. Special attention is paid to the band @Error-ControlWhen an error occurs with a operator prefix statement, this value is0。 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 user's function needs to accept two parameters: error code and description errorstring。 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 The first parameter errno, which contains the level of the error, is an integer. ERRSTR the second parameter errstr, which contains the wrong information, is astring。 Errfile The third parameter is optional, Errfile, which contains the name of the file where the error occurred, is astring。 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 reportsError_reporting (-1); function customerror($errno, $errmsg, $errfile, $errline ){    if(! (Error_reporting () &$errno)) {//This error code was not included in error_reporting        return; }Switch($errno) { CaseE_user_error:Echo "<b>my error</b> [$errno] $errmsg <br/>". Php_eol;Echo "Fatal error on line $errline in file $errfile";Echo ", PHP". Php_version." (". Php_os.") <br/>". Php_eol;Echo "Aborting...<br/>\n";//exit (1);         Break; CaseE_user_warning:Echo "<b>my warning</b> [$errno] $errmsg <br/>". Php_eol; Break; CaseE_user_notice:Echo "<b>my notice</b> [$errno] $errmsg <br/>". Php_eol; Break;default:Echo "Unknown error type: [$errno] $errmsg <br/>". Php_eol; Break; }/ * Don ' t execute PHP Internal Error handler * /    return true;} Set_error_handler (' Customerror ');Echo $test; Settype ($var,' King ');//Test ();Trigger_error (' something went wrong! ', E_user_error);Echo ' ;//Recovery error takeoverRestore_error_handler ();Echo $king;Echo ' ; Set_error_handler (' Customerror ', E_all&~e_notice);Echo ' ; Settype ($var,' King ');Echo ' The 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 [file in error] * @param [int] $errline [line number of error] * @param [ar Ray] $vars [array of all variables in 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 sending an email to an administrator             CaseE_user_error:return $self->dealerror (); Break; CaseE_user_warning: CaseE_warning:return $self->dealwarning (); Break; CaseE_user_notice: CaseE_notice:return $self->dealnotice (); Break;default://give PHP the error mechanism 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,"')            .$object.$call[' function '].' ('. Implode (', ',$call[' args '])            .') called at ['.$call[' file '].': '.$call[' line '].'] '; }returnImplode ("\ n",$ret); } 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=<<<eof A fatal error occurred, such as the file that generated the error: {$this->filename} generated the wrong message: {$this->msg} generated the wrong line number: {$this->LINE} tracking information: {$backtrace}\neof;Error_log ($ERRORMSG,1,' [email protected] ');Exit(1); }/** * [dealwarning Handling Warning Level ERROR] * @return [BOOL] */     Public  function dealwarning(){        $ERRORMSG=<<<eof A warning error occurred, such as the file that generated the warning: {$this->filename} The message that generated the warning: {$this->msg} The line number that generated the warning: {$this->line}\neof ;Error_log ($ERRORMSG,1,' [email protected] '); }/** * [dealnotice Processing notification level ERROR] * @return bool */     Public  function dealnotice(){        $datetime= Date (' y-m-d h:i:s ', time ());$ERRORMSG=<<<eof A notification error occurred, such as the file that generated the notification: {$this->filename} The information that generated the notification: {$this->msg} The line number that generated the notification: {$this->line} Time to generate notification: {$datetime}\neof;        returnError_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 1. function

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.

3.PHP Custom Error Handler

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.