3. PHP Custom Error Processor

Source: Internet
Author: User
3. PHP Custom Error Processor 1. Use set_error_handler to customize error handling function description
  • 1. create an error handling function
  • 2. set different levels of function calls
  • 3. the set_error_handler function specifies to take over error handling
  • Set_error_handler description

    Mixed set_error_handler (callable $ error_handler [, int $ error_types = E_ALL | E_STRICT]) sets a user's function (error_handler) to handle errors in the script. This function can be customized to handle running errors. for example, when a serious error occurs in an application, or an error is triggered under a specific condition (trigger_error (). you need to clear and recycle the data/files. It is important to remember that the error type specified in error_types bypasses the PHP Standard error handler unless the callback function returns FALSE. Error_reporting () settings will not work, and your error handling function will continue to be called ?? However, you can still get the current value of error_reporting and perform proper processing. Note that when an error occurs in a statement prefixed with @ error-control operator, the value is 0. Note that you have the responsibility to use die () when necessary (). If the error handler returns, the script will continue to execute the last line with the error. The following 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 most of the E_STRICT generated in the file where the set_error_handler () function is called. If an error occurs before the script is executed (such as when a file is uploaded), a custom error handler is not called because it is not yet registered at that time. The error_handler function must accept two parameters: the error code and the string with the wrong description. In addition, three optional parameters may be provided: the wrong file name, the wrong row number, and the context of the error (an array pointing to the active symbol table when the error occurs ). This function can be represented as: handler (int $ errno, string $ errstr [, string $ errfile [, int $ errline [, array $ errcontext]) errno the first parameter errno, contains the error level, which is an integer. Errstr, the second parameter of errstr, contains the error message, which is a string. The third parameter of errfile is optional. errfile contains the file name with an error and is a string. The fourth parameter of errline is optional. errline contains the row number of the error and is an integer. Errcontext is the fifth optional parameter. errcontext is an array pointing to the active symbol table when an error occurs. That is to say, errcontext contains an array of all variables in the scope of the error trigger. The user's error handler should not modify the context of the error ). If the function returns FALSE, the standard error handler will continue to call it. Error_types is the same as setting error_reporting ini to control the display of errors. this parameter can be used to block the triggering of error_handler. Without this mask, no matter how error_reporting is set, error_handler will be called when each error occurs.
    2. use of set_error_handler
    Header ('content-type: text/html; charset = utf-8 '); // enable all error reports: error_reporting (-1); function customError ($ errno, $ errmsg, $ errfile, $ errline) {if (! (Error_reporting () & $ errno) {// This error code is not supported 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 ('error! ', E_USER_ERROR); echo ''; // reclaim errors to take over restore_error_handler (); echo $ king; echo''; set_error_handler ('mermerror', E_ALL &~ E_NOTICE); echo ''; settype ($ var, 'king'); echo 'continue ...............';
    3. Custom error handling class
    /*** 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 code] * @ param [string] $ errmsg [error description] * @ param [string] $ Errfile [error file] * @ param [int] $ errline [error row number] * @ param [array] $ vars [array of all variables in the scope of error triggering] * @ return [bool] */public static function deal ($ errno, $ errmsg, $ errfile, $ errline, $ vars) {$ self = new self ($ errmsg, $ errfile, $ errline, $ vars); switch ($ errno) {// send a fatal error email to the administrator case E_USER_ERROR: return $ self-> dealError (); break; case E_USER_WARNING: case E_WARNING: return $ self-> dealWarning (); break; c Ase E_USER_NOTICE: case E_NOTICE: return $ self-> dealNotice (); break; default: // handle the return false; break with the php error mechanism ;}} 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_arr Ay ($ 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 ['. $ call ['file']. ':'. $ call ['line']. ']';} return implode ("\ 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 handle error-level errors] * @ return [type] [description] */public function dealError () {$ backtrace = $ this-> get_debug_print_backtrace (); echo $ backtrace; exit; $ errorMsg = <
     
      
    Filename} error message: {$ this-> msg} error row: {$ this-> line} trace information: {$ backtrace} \ n EOF; error_log ($ errorMsg, 1, '2017 @ qq.com '); exit (1 );} /*** [dealWarning handle warning-level errors] * @ return [bool] */public function dealWarning () {$ errorMsg = <
      
       
    Filename} generates warning information: {$ this-> msg} generates the warning row number: {$ this-> line} \ n EOF; error_log ($ errorMsg, 1, '1970 @ qq.com ');}/*** [dealNotice handle notification-level errors] * @ return bool */public function dealNotice () {$ datetime = date ('Y-m-d H: I: S', time (); $ errorMsg = <
       
        
    Filename} notification generation Information: {$ this-> msg} notification generation line number: {$ this-> line} notification generation Time: {$ datetime} \ n EOF; return error_log ($ errorMsg, 3, $ this-> _ noticeLog) ;}} error_reporting (-1); set_error_handler (array ('myerrorhandler', 'dest ')); ini_set ('display _ errors ', 0); echo $ var; trigger_error ('zhiming', E_USER_ERROR); trigger_error ('zhiming', E_USER_WARNING );
       
      
     
    4. use of the register_shutdown_function 1. function

    1. the register_shutdown_function allows us to set another function that can be called when the function is disabled.
    2. when the execution of our script is completed or the PHP execution is about to close due to unexpected death, our function will be called.

    2. use cases

    1. the page is forcibly stopped.
    2. unexpected termination or timeout of the program code

    3. Notes

    1. there cannot be termination functions such as die () exit () before register_shutdown_function

    Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

    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.