Home >Backend Development >PHP Tutorial >Introduction to Error handling and problem location under PHP5 (code example)

Introduction to Error handling and problem location under PHP5 (code example)

不言
不言forward
2019-01-09 10:38:102636browse

This article brings you an introduction to Error handling and problem location under PHP5 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Let’s talk about the problem locating method when PHP encounters an E_ERROR level fatal runtime error. For example, Fatal error: Allowed size memory ofmemory overflow. When this kind of error occurs, the program will exit directly. An error log will be recorded in PHP's error log indicating the specific file and number of lines of code where the error was reported, and no other information will be lost. If it is PHP7, you can catch errors like exceptions, but not with PHP5.

The generally thought of method is to look at the specific code of the error report. If the error file is CommonReturn.class.php, it will look like the following.

<?php

/**
 * 公共返回封装
 * Class CommonReturn
 */
class CommonReturn
{

    /**
     * 打包函数
     * @param     $params
     * @param int $status
     *
     * @return mixed
     */
    static public function packData($params, $status = 0)
    {
        $res[&#39;status&#39;] = $status;
        $res[&#39;data&#39;] = json_encode($params);
        return $res;
    }

}

The json_encode line reported an error, and then you checked the packData method. There are many project classes that call it. How to locate the problem?

Scene Reproduction

Okay, first let’s reproduce the scene. If the actually called program bug.php is as follows

<?php

require_once &#39;./CommonReturn.class.php&#39;;

$res = ini_set(&#39;memory_limit&#39;, &#39;1m&#39;);

$res = [];
$char = str_repeat(&#39;x&#39;, 999);
for ($i = 0; $i < 900 ; $i++) {
    $res[] = $char;
}

$get_pack = CommonReturn::packData($res);

// something else

When running bug.php, the PHP error log will record

[08-Jan-2019 11:22:52 Asia/Shanghai] PHP Fatal error:  Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes) in /CommonReturn.class.php on line 20

that the reproduction was successful. The error log only explains the file and line of code where the error was reported. , it is impossible to know the context stack information of the program, and does not know which piece of business logic is called, so it is impossible to locate and fix the error. How to troubleshoot if it occurs occasionally and there is no feedback from the front-end business.

Solution ideas

1. Some people thought of modifying memory_limit to increase memory allocation, but this method treats the symptoms but not the root cause. When doing development, you must find the root cause of the problem.

2. Turn on core dump. If the code file is generated, it can be debugged. However, it is found that the code will only be generated when the process exits abnormally. Errors at the E_ERROR level may not necessarily generate code files. The possibility of memory overflow is handled by PHP internally.

3. Use register_shutdown_function to register a callback function when PHP terminates, and then call error_get_last. If the last error that occurred is obtained, use debug_print_backtrace to obtain the stack information of the program. Let's try it.

Modify the CommonReturn.class.php file as follows

<?php

/**
 * 公共返回封装
 * Class CommonReturn
 */
class CommonReturn
{

    /**
     * 打包函数
     * @param     $params
     * @param int $status
     *
     * @return mixed
     */
    static public function packData($params, $status = 0)
    {

        register_shutdown_function([&#39;CommonReturn&#39;, &#39;handleFatal&#39;]);

        $res[&#39;status&#39;] = $status;
        $res[&#39;data&#39;] = json_encode($params);
        return $res;
    }

    /**
     * 错误处理
     */
    static protected function handleFatal()
    {
        $err = error_get_last();
        if ($err[&#39;type&#39;]) {
            ob_start();
            debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
            $trace = ob_get_clean();
            $log_cont = &#39;time=%s&#39; . PHP_EOL . &#39;error_get_last:%s&#39; . PHP_EOL . &#39;trace:%s&#39; . PHP_EOL;
            @file_put_contents(&#39;/tmp/debug_&#39; . __FUNCTION__ . &#39;.log&#39;, sprintf($log_cont, date(&#39;Y-m-d H:i:s&#39;), var_export($err, 1), $trace), FILE_APPEND);
        }

    }

}

Run bug.php again, the log is as follows.

error_get_last:array (
  &#39;type&#39; => 1,
  'message' => 'Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes)',
  'file' => '/CommonReturn.class.php',
  'line' => 23,
)
trace:#0  CommonReturn::handleFatal()

The traceback information has no source, which is embarrassing. I guess because the backtrace information is stored in memory and will be cleared when a fatal error occurs. There is no other way, try passing the backtrace in from the outside. Modify CommonReturn.class.php again.

<?php

/**
 * 公共返回封装
 * Class CommonReturn
 */
class CommonReturn
{

    /**
     * 打包函数
     * @param     $params
     * @param int $status
     *
     * @return mixed
     */
    static public function packData($params, $status = 0)
    {

        ob_start();
        debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
        $trace = ob_get_clean();
        register_shutdown_function([&#39;CommonReturn&#39;, &#39;handleFatal&#39;], $trace);

        $res[&#39;status&#39;] = $status;
        $res[&#39;data&#39;] = json_encode($params);
        return $res;
    }

    /**
     * 错误处理
     * @param $trace
     */
    static protected function handleFatal($trace)
    {
        $err = error_get_last();
        if ($err[&#39;type&#39;]) {
            $log_cont = &#39;time=%s&#39; . PHP_EOL . &#39;error_get_last:%s&#39; . PHP_EOL . &#39;trace:%s&#39; . PHP_EOL;
            @file_put_contents(&#39;/tmp/debug_&#39; . __FUNCTION__ . &#39;.log&#39;, sprintf($log_cont, date(&#39;Y-m-d H:i:s&#39;), var_export($err, 1), $trace), FILE_APPEND);
        }

    }

}

Run bug.php again, the log is as follows.

error_get_last:array (
  &#39;type&#39; => 1,
  'message' => 'Allowed memory size of 1048576 bytes exhausted (tried to allocate 525177 bytes)',
  'file' => '/CommonReturn.class.php',
  'line' => 26,
)
trace:#0  CommonReturn::packData() called at [/bug.php:13]

Successfully located the source of the call, which is on line 13 of bug.php. Publish the final CommonReturn.class.php to the production environment, and just look at the log when an error occurs again. But in this case, all programs that call packData will execute the trace function, which will definitely affect performance.

Summary

  1. You need to pay attention to the register_shutdown_function function used. You can register multiple different callbacks, but if a certain callback function If you exit, any callback functions registered later will not be executed.

  2. debug_print_backtrace This function to obtain backtrace information first contains request parameters, and the second is the number of backtrace record levels. We do not return request parameters here, which can save some memory, and if If the request parameters are huge, calling this function may cause memory overflow.

  1. The best way is to upgrade PHP7, which can catch errors like exceptions.


The above is the detailed content of Introduction to Error handling and problem location under PHP5 (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete