PHP中错误处理的一些方法
http://tech.ddvip.com 2007年09月17日 社区交流
内容摘要:本文介绍PHP中错误处理的一些方法
而后,注意了,如果您第一次(或者重新)加载的话,就加上:
set_error_handler('error_handler');
set_exception_handler('exception_handler');
如果不是上述情况,就不要加了,否则会出现
ExceptionthrownwithoutastackframeinUnknownonline0
因为error_handler是anto_flush的。
在一个exception里面不能调用其他的exception。有2条普遍适用的规则,如下:
1:不要在一个Exception里面执行另一个Exception
2:不要在析构函数里面执行Exception.
restore_exception_handler();是可以保存exception柄的,注意,执行error以后就会有Exception的了。
最后,加上一个完整的例子:CallError.php
<?
error_reporting(1048);
classErrorHandlersextendsException{
private$_context=null;
function __construct($level, $string, $file, $line, $context=null){
parent::__construct($string,$level);
$this->file = $file;
$this->line = $line;
$this->_level = $level;
$this->_context = $context;
}
function__destruct(){
// parent::__destruct();
}
functionMessage(){
$errors=array(
E_ERROR =>'error',
E_WARNING =>'warning',
E_PARSE =>'parsingerror',
E_NOTICE =>'notice',
E_CORE_ERROR =>'coreerror',
E_CORE_WARNING =>'corewarning',
E_COMPILE_ERROR =>'compileerror',
E_COMPILE_WARNING=>'compilewarning',
E_USER_ERROR =>'usererror',
E_USER_WARNING =>'userwarning',
E_USER_NOTICE =>'usernotice'
);
$str=$errors[parent::getCode()].':'.parent::getMessage().'在'.parent::getFile().
'的第'.parent::getLine()."行
";
if($this->_level==E_USER_ERROR){
$str.=('<hr/>致命错误');
}
echo('<pre>');
echo($str);
echo('</pre>');
}
}
functionerror_handler($errno,$errstr,$errorfile,$errline,$errtext){
thrownewErrorHandlers($errno,$errstr,$errorfile,$errline,$errtext);
}
functionexception_handler(Exception$e)
{
$errors=array(
E_ERROR =>'error',
E_WARNING =>'warning',
E_PARSE =>'parsingerror',
E_NOTICE =>'notice',
E_CORE_ERROR =>'coreerror',
E_CORE_WARNING =>'corewarning',
E_COMPILE_ERROR =>'compileerror',
E_COMPILE_WARNING=>'compilewarning',
E_USER_ERROR =>'usererror',
E_USER_WARNING =>'userwarning',
E_USER_NOTICE =>'usernotice');
echo$errors[$e->getCode()].':'.$e->getMessage().'在'.$e->getFile().
'的第'.$e->getLine()."行
";
echo$e->getMessage();
die();
}
//
set_error_handler('error_handler');
//restore_error_handler();
set_exception_handler('exception_handler');
//restore_exception_handler();
我肯定是错误
?>
执行结果:
notice:Useofundefinedconstant我肯定是错误-assumed'我肯定是错误'在E:webwebphpiexceptionm.php的第74行Useofundefinedconstant我肯定是错误-assumed'我肯定是错误'

另外,在类中,还可以这样:
functiontrigger_error($error_msg,$error_type=E_USER_WARNING)
{
trigger_error("error:$error_msg",$error_type);
}
著名的Smarty就是这么做的.
责编:豆豆技术应用
- php 正则表达式
- php 入门教程
- php 安装配置
- php 函数专题
- php 函数大全(EN)
- php 5.0 中文手册
- php 4.0 中文手册
- php 程序编码规范标准
- php 常见错误
- php 中文乱码
- php Apache 安装配置
- linux php 安装配置
- windows php 安装配置
- php 十天入门教程
- php 学习笔记
- php smarty 教程
- php 分页专题
- php 类
- php 变量
- php 常量
- php 数组
- php 脚本
- php 入门实例
- php 字符串
- php.ini 配置
- php xml 专题
- php session 教程
- php 对象模型
- 更多php专题……