PHP中的错误处理_PHP教程

WBOY
Release: 2016-07-13 17:51:36
Original
780 people have browsed it

程序只要在运行,就免不了会出现错误!或早或晚,只是时间问题罢了。
错误很常见,比如Notice,Warning等等。此时一般使用set_error_handler来处理:

set_error_handler(function($errno, $errstr, $errfile, $errline) {
var_dump($errno, $errstr, $errfile, $errline);
});

// Notice: Use of undefined constant strlen
strlen;

// Warning: strlen() expects exactly 1 parameter, 0 given
strlen();

?>
具体能做些什么呢?统一管理错误日志,或者呈现一个相对友好的错误提示页面等等。
但需要注意的是set_error_handler无法捕捉某些Fatal error,比如下面这个错误:

set_error_handler(function($errno, $errstr, $errfile, $errline) {
var_dump($errno, $errstr, $errfile, $errline);
});

// Fatal error: Call to undefined function undefined_function()
undefined_function();

?>
不过我们真的就一点办法都没有了么?当然不是,我们不仅有办法,而且还有好几种:
第一种:ob_start + error_get_last

ob_start(function($buffer) {
if ($error = error_get_last()) {
return var_export($error, true);
}

return $buffer;
});

// Fatal error: Call to undefined function undefined_function()
undefined_function();

?>
第二种:register_shutdown_function + error_get_last

register_shutdown_function(function() {
if ($error = error_get_last()) {
var_dump($error);
}
});

// Fatal error: Call to undefined function undefined_function()
undefined_function();

?>
此外,所有的Parse error都无法捕捉,不过换个角度看,解析错误的代码本身就不应该发布,甚至都不应该进入版本库,关于这一点,我以前写过一篇《Subversion钩子》,里面介绍了如何利用Subversion钩子做代码语法检查。
似乎应该顺水推舟接着写点介绍异常的文字才好,可惜时间不早了,还是洗洗睡吧。

作者 老王

www.bkjia.com true http://www.bkjia.com/PHPjc/478184.html TechArticle 程序只要在运行,就免不了会出现错误!或早或晚,只是时间问题罢了。 错误很常见,比如Notice,Warning等等。此时一般使用set_error_handle...
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!