<?php
/**
* PHP錯誤:是屬於php程序自身的問題,一般是由非法的語法,環境問題導致的,使得編譯器無法通過檢查,甚至無法運行的情況。平時遇到的warming、notice都是錯誤,只是級別不同而已。
* PHP異常:一般是業務邏輯上出現的不合預期、與正常流程不同的狀況,不是語法錯誤。
*
* PHP無法自動捕獲錯誤和異常,以下實例運行,直接報錯
* try {
* echo $ary[0];
* } catch (Exception $e) {
* echo $e->getMessage();
* }
*
* 必須要自己拋出異常,如下就可以了
* try {
* if(isset($ary)){
* echo $ary[0];
* }else{
* Throw new Exception('此函數不存在',400);
* }
* } catch (Exception $e) {
* echo $e->getMessage();
* }
*
* 手動拋出異常實在是不實用,怎么進行自動捕獲錯誤和異常呢?使用set_exception_handler()
* set_exception_handler('_exception_handler');
* function _exception_handler(Throwable $e){
* if ($e instanceof Error) {
* echo "catch Error: " . $e->getCode() . ' ' . $e->getMessage() . '<br>';
* } else {
* echo "catch Exception: " . $e->getCode() . ' ' . $e->getMessage() . '<br>';
* }
* }
* foobar(3, 5); //調用未定義的方法將會產生一個Error級別的錯誤
* throw new Exception('This is a exception', 400); //拋出一個Exception
*
* 自動捕獲錯誤,使用set_error_handler()
* set_error_handler('_error_handler', E_ALL | E_STRICT);
* function _error_handler($errno, $errstr, $errfile, $errline)
* {
* echo "錯誤編號errno: $errno<br>";
* echo "錯誤信息errstr: $errstr<br>";
* echo "出錯文件errfile: $errfile<br>";
* echo "出錯行號errline: $errline<br>";
* }
* echo $foo['bar']; // 由於數組未定義,會產生一個notice級別的錯誤
*
* 但以下級別的錯誤不能由用戶定義的函數來處理:
* E_ERROR、E_PARSE、E_CORE_ERROR、E_CORE_WARNING、E_COMPILE_ERROR、E_COMPILE_WARNING,
* 和在 調用 set_error_handler() 函數所在文件中產生的大多數 E_STRICT。
* 捕獲Fatal Error錯誤
* ExceptionDemo.php 代碼如下
* ExceptionDemo1.php
* error_reporting(0);
* require './ExceptionDemo.php';
* require './ExceptionDemo2.php'; //ExceptionDemo1.php 本身語法並沒有出錯,也就是在parse-time的時候並沒有出錯,而是require文件時出錯了,也就是在run-time的時候出錯了,這個時候是能回調 register_shutdown_function()中的函數的。
* ExceptionDemo2.php
* function test(){}
* function test(){} //訪問ExceptionDemo2.php文件時,php的語法解析器在parse-time的時候就出錯了,不能回調register_shutdown_function()中的方法
*
*/
register_shutdown_function("fatal_handler");
set_error_handler("error_handler");
define('E_FATAL', E_ERROR | E_USER_ERROR | E_CORE_ERROR |
E_COMPILE_ERROR | E_RECOVERABLE_ERROR | E_PARSE);
//獲取 fatal error
function fatal_handler()
{
$error = error_get_last();
if ($error && ($error["type"] === ($error["type"] & E_FATAL))) {
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
error_handler($errno, $errstr, $errfile, $errline);
}
}
//獲取所有的 error
function error_handler($errno, $errstr, $errfile, $errline)
{
$str = <<<EOF
"errno":$errno
"errstr":$errstr
"errfile":$errfile
"errline":$errline
EOF;
//獲取到錯誤可以自己處理,比如記 Log、報警等等
echo $str;
}
?>