php 7 中对 error 的处理
在 php 5 中,当程序中有致命错误发生时,脚本会立即停止运行。并且,通过 set_error_handler 设置的错误处理程序在这种情况下并不会被调用。
【推荐学习:php7教程】
⒈ 自定义错误处理程序 set_error_handler
set_error_handler 接受两个参数,第一个为自定义的错误处理函数,第二个参数指定触发该自定义错误处理函数的错误级别。但需要指出的是,在任何时候,只能有一个自定义的错误处理程序起作用。
function func_notice($num, $str, $file, $line) { print "encountered notice $num in $file, line $line: $str\n";}function func_error($num, $str, $file, $line) { print "encountered error $num in $file, line $line: $str\n";}set_error_handler("func_notice", e_notice);set_error_handler("func_error", e_error);echo $foo;
以上代码在执行以后,会输出 php notice: undefined variable: foo 。在第二个 set_error_handler 执行以后,自定义错误处理函数变成了 func_error ,同时,触发自定义错误处理函数的错误级别变成了 e_error 。而在 php 中,变量未定义只会触发 e_notice 级别的错误,所以自定义的错误处理函数并不会被触发。
需要指出的是,自定义的错误处理函数对以下几种错误级别并不起作用:
e_error、e_parse、e_core_error、e_core_warning、e_compile_error、e_compile_warning、e_strict
在上述几种自定义错误处理程序无法处理的错误中,凡是以 error 结尾的都是致命错误。其他几种虽然不是致命错误,但
e_parse 是在解析 php 代码时产生的错误,此时 php 代码尚未开始运行,自定义错误处理程序自然无法处理该错误
e_core_warning 产生于 php 的初始化启动阶段,此时 php 代码仍然尚未运行,所以不能被自定义错误处理程序处理
e_compile_warning 是在 php 代码的编译阶段产生,所以不能被自定义错误处理程序处理
而至于 e_strict 是 php 为了保证代码的最佳互操作性和向前兼容而提出的代码修改建议,自然也不会被自定义错误处理函数处理
function func_error($num, $str, $file, $line) { print "encountered error $num in $file, line $line: $str\n";}set_error_handler('func_error', e_notice);$obj = 'foo';$obj->method();
以上代码运行输出结果:
php fatal error: call to a member function method() on string
虽然设置了自定义错误处理程序,但在致命错误发生时,并不起作用。
对于这种自定义错误处理程序无法处理的致命错误,在 php 5 中可以通过注册一个终止回调(shutdown_function)来记录具体的错误信息,但也仅限于记录错误信息,当发生致命错误时代码仍然会停止运行。
$shutdownhandler = function(){ print php_eol; print "============================" . php_eol; print "running the shutdown handler" . php_eol; $error = error_get_last(); if (!empty($error)) { print "looks like there was an error: " . print_r($error, true) . php_eol; // 可以添加记录日志的逻辑 } else { // 程序正常运行结束 print "running a normal shutdown without error." . php_eol; }};register_shutdown_function($shutdownhandler);$obj = 'foo';$obj->method();
以上代码执行会输出
php fatal error: call to a member function method() on string in /home/chenyan/test.php on line 24============================running the shutdown handlerlooks like there was an error: array( [type] => 1 [message] => call to a member function method() on string [file] => /home/chenyan/test.php [line] => 24)
⒉ 撤销自定义错误处理程序
当同时设置多个自定义错误处理程序时,虽然只有最后设置的自定义错误处理程序起作用。但所有设置的自定义错误处理程序会以栈的方式保存(filo)。
使用 restore_error_handler 可以撤销最近一次设置的自定义错误处理程序;如果同时调用了多次 set_error_handler ,则每调用一次 restore_error_handler,处于栈顶的错误处理程序就会被撤销。
function func_notice($num, $str, $file, $line) { print "encountered notice : $str\n";}set_error_handler("func_notice", e_notice);set_error_handler("func_notice", e_notice);set_error_handler("func_notice", e_notice);echo $foo;set_error_handler("func_notice", e_notice);echo $foo;restore_error_handler();echo $foo;restore_error_handler();echo $foo;restore_error_handler();echo $foo;restore_error_handler();echo $foo;
以上代码运行,会输出:
encountered notice : undefined variable: fooencountered notice : undefined variable: fooencountered notice : undefined variable: fooencountered notice : undefined variable: fooencountered notice : undefined variable: foophp notice: undefined variable: foo
⒊ php 7 中对错误的处理
在 php 7 中,当有致命错误或 e_recoverable_error 类型的错误发生时,通常会抛出一个 error,程序并不会终止。
try { $obj = 'foo'; $obj->method();} catch (\error $e) { echo $e->getmessage();}
运行以上代码会输出
call to a member function method() on string
e_recoverable_error 是一种可捕获的致命错误,这种错误的出现并不会使得 zend 引擎处于不稳定的状态,但必须被捕获并且处理。如果不处理,那么这种错误最终会变成 e_error 类型的错误,最终导致 php 代码停止运行。
php 7 中,并不是所有的致命错误都会抛出 error,一些特定情况下出现的致命错误( out of memory)仍然会导致代码停止运行。另外,如果抛出的 error 没有被捕获并处理,则代码仍然会停止运行。
// bak.sql 的大小为 377 m// php 配置的 memory_limit = 128mtry { $file = './bak.sql'; file_get_contents($file);} catch (\error $e) { echo $e->getmessage();}// 执行以上代码,仍然会产生致命错误php fatal error: allowed memory size of 134217728 bytes exhausted (tried to allocate 395191240 bytes)// 抛出的 error 没有被捕获并处理,代码依然会停止运行$obj = 'foo';$obj->method();// 执行以上代码,由于并没有用 try/catch 捕获并处理抛出的 error,程序仍然会停止运行php fatal error: uncaught error: call to a member function method() on string
php 7 中的 error 并没有继承 exception,之所以这样做是为了防止 php 5 中捕获并处理 exception 的代码捕获这些 error。因为在 php 5 中,这些致命错误是会导致代码停止运行的。
error 和 exception 都继承自 throwable 。在 php 7 中,throwable 是一个 interface,所有能通过 throw 关键字抛出的对象都实现了这个 interface。
interface throwable{ public function getmessage(): string; public function getcode(): int; public function getfile(): string; public function getline(): int; public function gettrace(): array; public function gettraceasstring(): string; public function getprevious(): throwable; public function __tostring(): string;}
需要指出的是,throwable 是 php 底层的 interface,php 代码中不能直接实现 throwable 。之所以作出这个限制,是因为通常只有 error 和 exception 可以被抛出,并且这些抛出的 error 和 exception 中还存储了它们被抛出的堆栈跟踪信息,而 php 代码中开发者自定义的 class 无法实现这些。
要在 php 代码中实现 throwable 必须通过继承 exception 来实现。
interface customthrowable extends throwable {}class customexception extends exception implements customthrowable {}throw new customexception();
php 7 中 error 和 exception 的继承关系
interface throwable |- exception implements throwable |- other exception classes |- error implements throwable |- typeerror extends error |- parseerror extends error |- assertionerror extends error |- arithmeticerror extends error |- divizionbyzeroerror extends arithmeticerror
typeerror
当函数的传参或返回值的数据类型与申明的数据类型不一致时,会抛出 typeerror
function add(int $left, int $right){ return $left + $right;}try { $value = add('left', 'right');} catch (typeerror $e) { echo $e->getmessage();}// 运行以上代码,会输出:argument 1 passed to add() must be of the type int, string given
当开启严格模式时,如果 php 内建函数的传参个数与要求的参数不一致,也会抛出 typeerror
declare(strict_types = 1);try { substr('abc');} catch (typeerror $e) { echo $e->getmessage();}// 运行以上代码,会输出:substr() expects at least 2 parameters, 1 given
默认情况下,php 7 处于弱模式。在弱模式下,php 7 会尽可能的将传参的数据类型转换为期望的数据类型。例如,如果函数期望的参数类型为 string,而实际传参的数据类型的 int,那么 php 会把 int 转换为 string。
// declare(strict_types = 1);function add(string $left, string $right){ return $left + $right;}try { $value = add(11, 22); echo $value;} catch (typeerror $e) { echo $e->getmessage();}// 以上代码运行,会正常输出 33,php 会对传参的数据类型做转换(int→string→int)// 但如将 php 改为严格模式,则运行是会抛出 typeerrorargument 1 passed to add() must be of the type string, int given
parseerror
当在 include 或 require 包含的文件中存在语法错误,或 eval() 函数中的代码中存在语法错误时,会抛出 parseerror
// a.php$a = 1$b = 2// test.phptry { require 'a.php';} catch (parseerror $e) { echo $e->getmessage();}// 以上代码运行会输出:syntax error, unexpected '$b' (t_variable)// eval 函数中的代码存在语法错误try { eval("$a = 1");} catch (parseerror $e) { echo $e->getmessage();}// 以上代码运行会输出:syntax error, unexpected end of file
assertionerror
当断言失败时,会抛出 assertionerror(此时要求 php 配置中 zend.assertions = 1,assert.exception = 1,这两个配置可以在 php.ini 文件中配置,也可以通过 ini_set() 在 php 代码中配置)。
ini_set('zend_assertions', 1);ini_set('assert.exception', 1);try { $test = 1; assert($test === 0);} catch (assertionerror $e) { echo $e->getmessage();}// 运行以上代码会输出:assert($test === 0)
arithmeticerror
在 php 7 中,目前有两种情况会抛出 arithmeticerror:按位移动操作,第二个参数为负数;使用 intdiv() 函数计算 php_int_min 和 -1 的商(如果使用 / 计算 php_int_min 和 -1 的商,结果会自动转换为 float 类型)。
try { $value = 1 << -1;} catch (arithmeticerror $e) { echo $e->getmessage();}// 运行以上代码,会输出:bit shift by negative numbertry { $value = intdiv(php_int_min, -1);} catch (arithmeticerror $e) { echo $e->getmessage();}// 运行以上代码,会输出:division of php_int_min by -1 is not an integer
divisionbyzeroerror
抛出 divisionbyzeorerror 的情况目前也有两种:在进行取模(%)运算时,第二个操作数为 0;使用 intdiv() 计算两个数的商时,除数为 0。如果使用 / 计算两个数的商时除数为 0,php 只会产生一个 warning。并且,如果被除数非 0,则结果为 inf,如果被除数也是 0,则结果为 nan。
try { $value = 1 % 0; echo $value;} catch (divisionbyzeroerror $e) { echo $e->getmessage(), "\n";}// 运行以上代码,会输出:modulo by zerotry { $value = intdiv(0, 0); echo $value;} catch (divisionbyzeroerror $e) { echo $e->getmessage(), "\n";}// 运行以上代码,会输出:division by zero
通常在实际的业务中,捕获并处理抛出的 error 并不常见,因为一旦抛出 error 说明代码存在严重的 bug,需要修复。所以,在实际的业务中,error 更多的只是被用来捕获并记录具体的错误日志,然后通知开发者进行 bug 修复。
以上就是聊聊在php7中对于error的处理是怎样的的详细内容。