php中的错误处理机制

1.如果没有错误处理机制会怎样?

 

案例1

<?php
 $fp=fopen("aa.txt","r");//打开文件,没有验证,是否存在该文件?
 echo "ok";
 
?>

 

结果

Warning: fopen(aa.txt) [function.fopen]: failed to open stream: No such file or directory in E:\Software_default\wamp_wwwroot\error\error01.phpon line 2

ok

 

来自 <http://localhost/error/error01.php>

 

改进

 

案例2

<?php
 if(file_exists("aa.txt"))//绝对路径
 {
 echo "ok";
 $fp=fopen("aa.txt","r");//打开文件
 fclose($fp);
 }
 else
 {
 echo "no file";
 exit();
 }
?>

 

2.简单的die()语句

 

 die()语法结构等同于 exit().

 die处理错误三张方式:

1.使用简单的die()语句;

2.使用 file_exists("aaa.txt") or die("no file");

 

使用die()处理以上例子

 

案例3

<?php
 if(file_exists("aaa.txt"))//绝对路径
 {
 echo "ok";
 $fp=fopen("aa.txt","r");//打开文件
 fclose($fp);
 }
 else
 {
 die("no
file");
 }
?>

 

或者更简洁的写法

 

案例4

<?php
 file_exists("aaa.txt") or
die("no file");
 
?>

3.创建自定义函数处理错误

 

      php中,如果出现错误,会启动默认机制处理错误的方式来处理错误。如案例1,如果没有存在aa.txt,php将提示

Warning: fopen(aa.txt) [function.fopen]: failed to open stream: No such file or directory in E:\Software_default\wamp_wwwroot\error\error01.php on line 2

 

因此我们可以自定义错误方式来代替php默认错误机制

(1).创建自定义错误函数

函数必须有能力处理至少两个参数(error level , error message),但是可以接受最多5个参数(可选:flie,line-number,error context

(2).基本语法

.error_function(error_level ,error_message,error_flie,error_line,error_context)

.同时改写 set_error_handle("error_function",错误级别),错误级别如下图:

其中,出现warning时,不会暂停脚本运行

案例5

<?php
 
 function my_error($errno,$errmes)
 {
 echo "<strong>错误级别</strong>:<font
color='red'>".$errno."</font><br>";
 echo "<strong>错误信息</strong>:".$errmes;
 }
 set_error_handler("my_error",E_WARNING);
 echo "测试打开aaa.txt<br>";
 $fp=fopen("aaa.txt","r");//打开文件
?>

4.错误触发器

 

      需求:有一段代码,如果input接受一个年龄,假如年龄大于100,我认为是一个错误。

//传统方法:

案例6

If($age>100)

{

  echo "too old";

  exit();

}

现在可以使用自定义错误触发器

案例7

<?php
 $age=700;
 echo
"age:".$age."<br>";
 
 if($age>100)
 {
 trigger_error("年龄太大");
 exit();
 }
?>

结果:

age:700

 

Notice: 年龄太大 in E:\Software_default\wamp_wwwroot\error\error05.phpon line 7

 

来自 <http://localhost/error/error05.php>

从案例7,我们可以发现,使用了trigger_error(),相当于触发了一个错误,从而调用php默认错误提示机制,因此,在此情况下,还可以进行改写错误函数,即自定义错误函数。

 

其中,trigger_error()里有两个参数,trigger_error("error_msg",error_type),默认为E_USER_NOTICE,可选有:

E_USER_WARNING,E_USER_ERROR,根据需求选择。

 

注意:此处的错误级别通常为:E_USER_WARNING,E_USER_NOTICE,E_USER_ERROR

根据需求选择适当类型,由于案例7出现notice错误,所以此处,我们应该选择E_USER_NOTICE

案例8

<?php
 
function
age_error($erroro,$erromes)
  {
  
echo "<strong>错误级别</strong>:<font
color='red'>".$erroro."</font><br>";
  
echo "<strong>错误信息</strong>:".$erromes;
  }
 set_error_handler("age_error",E_USER_NOTICE);//错误级别通常为:E_USER_WARNING,E_USER_NOTICE,E_USER_ERROR
 
 $age=700;
 echo
"age:".$age."<br>";
 
 if($age>100)
 {
 trigger_error("年龄太大,大于120");//默认是E_USER_NOTICE
 exit();
 }
 
?>

结果如下:

age:700

错误级别:1024

错误信息:年龄太大,大于120

 

来自 <http://localhost/error/error06.php>

 

 

 

 


发布了19 篇原创文章 · 获赞 16 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/wmin510/article/details/51472000