ITeye博客

处理PHP的致命错误(Fatal Error 或 E_ERROR)

wj45 · 2011-01-14 16:45 · 编程语言 · Markdown

如何处理PHP的E_ERROR或Fatal Error是一件麻烦事。当程序因为内存不足、执行超时等等而出现致命错误意外中断时,也需要进行相关的处理,而这时error_reporting与try...catch都不适用。

这时可以利用PHP的register_shutdown_function函数。

手册上写的很明确:register_shutdown_function — Register a function for execution on shutdown,就是说当程序中断时会调用该函数注册的函数。

比如:


<?php
function shutdown() {
    echo 'Script executed with success', PHP_EOL;
}
register_shutdown_function('shutdown');
?> 

当然,任何的程序中断都会触发用此方法注册的函数,包括exit()等等。如果想只用来处理某段程序的致命错误,这时需要进行一下判断,可以参考一下代码:


<?php
class Test {
	private $running;
	
	public function __construct() {
		register_shutdown_function(array($this, 'shutdown_handler'));
	}
	
	public function main() {
		$this->running = true;  //开始监测	
		echo "Hello ";
		$this->error();  //(undefined method)触发一个致命错误
		echo "World ";      	
		$this->running = false;  //结束监测
	}
	
	public function shutdown_handler() {
		if ($this->running) {
			echo '抱歉出错了~';
			@header("Location: error.php");   
		}
	}
}

$t = new Test();
$t->main();
?>

更新:其实这里可以使用error_get_last()函数来获取最后一条错误


<?php
	public function shutdown_handler() {
		$error = error_get_last();
		if ($error['type'] == 1) {  //只针对E_ERROR
			echo '抱歉出错了~';
			@header("Location: error.php");   
		}
	}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。