Home  >  Article  >  Backend Development  >  How to catch errors in PHP

How to catch errors in PHP

不言
不言Original
2018-07-07 16:04:332314browse

This article mainly introduces the method of catching errors in PHP, which has certain reference value. Now I share it with you. Friends in need can refer to it.

PHP catching errors

  • Disable error output

error_reporting(0);
  • Set error handler

set_error_handler('errorHandler');
  • function to run at the end of the script

register_shutdown_function('fatalErrorHandler');
  • Error handling

/**
 * @param int    $err_no      错误代码
 * @param string $err_msg  错误信息
 * @param string $err_file    错误文件
 * @param int    $err_line     错误行号
 * @return string
 */
function errorHandler($err_no = 0, $err_msg = '', $err_file = '', $err_line = 0)
{
    $log = [
        '['.date('Y-m-d h-i-s').']',
        '|',
        $err_no,
        '|',
        $err_msg,
        '|',
        $err_file,
        '|',
        $err_line
    ];
    $log_path = './test.txt';
    error_log(implode(' ',$log)."\r\n",3, $log_path);
}
  • Catching fatal errors

function fatalErrorHandler() {
    $e = error_get_last();

    var_export($e);
    switch ($e['type']) {
        case 1:
            errorHandler($e['type'], $e['message'], $e['file'], $e['line']);
            break;
    }
}
class DemoClass_1
{
    public function index()
    {
        //这里发生一个警告错误,出发errorHandler
        echo $undefinedVarible;
    }
}
  • A warning error occurred here and was captured by errorHandler

$demo_1 = new DemoClass_1();
$demo_1->index();
  • A fatal error occurs and the script stops running and triggers fatalErrorHandler

$demo_2 = new DemoClass_2();
$demo_2->index();

After opening test.txt, the output is:

[2018-06-12 05-49-11] | 8 | Undefined variable: undefinedVarible | /Users/darry/htdocs/test.php | 57
[2018-06-12 05-49-11] | 1 | Uncaught Error: Class 'DemoClass_2' not found in /Users/darry/htdocs/test.php:67
Stack trace:
#0 {main}
  thrown | /Users/darry/htdocs/test.php | 67

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

related suggestion:

Nginx SSL fast two-way authentication configuration (script)

Recursion based on PHP data structure

About the use of thinkphp behavior

The above is the detailed content of How to catch errors in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn