您好,欢迎访问一九零五行业门户网

PHP中的异常处理

1.什么是异常?异常和错误有什么区别? 1.异常:程序运行与预期不太一致,与错误是两个不同的概念!
2.抛出和捕获异常
3.多个catch块的时候基类要往后放,否则基类捕获异常后就不会往下继续捕获了!
3.先出现错误,在出现异常,所以写api的时候一定要把display_errors关掉
4.php的内置异常
error_reporting(-1);ini_set('display_errors','off');//pdo内置异常类try { $pdo = new pdo('mysql:host=localhost;dbname=mysql', 'brave', '123456'); var_dump($pdo); echo ''; echo 'continue.......';} catch (exception $e) { echo $e->getmessage();}echo 'this is a test.......';echo '';//spl文件读写内置异常类try { $splobj = new splfileobject('test.txt', 'r'); echo 'read file';} catch (runtimeexception $e) { echo $e->getmessage();}echo 'continue.......';echo '';
2.异常的基本语法结构 try { //需要进行异常处理的代码 throw语句抛出 } catch (pdoexception $e) { try { throw语句抛出 } catch (exception $e) { } } catch (fileexception $e) { } catch (customexception $e) { } //other code
3.如何自定义异常类? error_reporting(-1);ini_set('display_errors','off');class myexception extends exception{ function __construct($message, $code=0) { parent::__construct($message, $code); } public function __tostring(){ $message = 出现异常了,信息如下; $message .=.__class__. [{$this->code}]:{$this->message}
; return $message; } public function test(){ echo 'this is a test'; } public function stop(){ exit('script end..............'); } //自定义其他方法}try { echo '出现异常了!'; throw new myexception(测试自定义异常!, 11);} catch (myexception $e) { echo $e->getmessage(); echo ''; echo $e; echo ''; $e->stop(); $e->test();}
4.自定义文件异常类 error_reporting(-1);ini_set('display_errors','off');class fileexception extends exception { public function getdetails() { switch ($this->code) { case 0: return '没有提供文件!'; break; case 1: return '文件不存在!'. trace.$this->gettraceasstring().$this->getline(); break; case 2: return '不是一个文件!'. trace.$this->gettraceasstring().$this->getline(); break; case 3: return '文件不可写!'; break; case 4: return '非法文件的操作模式!'; break; case 5: return '数据写入失败!'; break; case 6: return '文件不能被关闭!'; break; default: return '非法!'; break; } }}class writedata{ private $_message=''; private $_fp=null; public function __construct($filename=null, $mode='w'){ $this->_message=文件:{$filename} 模式:{$mode}; if (empty($filename)) { throw new fileexception($this->_message, 0); } if (!file_exists($filename)) { throw new fileexception($this->_message, 1); } if (!is_file($filename)) { throw new fileexception($this->_message, 2); } if (!is_writable($filename)) { throw new fileexception($this->_message, 3); } if (!in_array($mode, array('w', 'w+', 'a', 'a+'))) { throw new fileexception($this->_message, 4); } $this->_fp=fopen($filename, $mode); } /** * [write 写数据] * @param [type] $data [description] * @return [type] [description] */ public function write($data){ if (@!fwrite($this->_fp, $data.php_eol)) { throw new fileexception($this->_message, 5); } } /** * [close 关闭文件句柄] * @return [type] [description] */ public function close(){ if ($this->_fp) { if (@!fclose($this->_fp)) { throw new fileexception($this->_message, 6); $this->_fp=null; } } } public function __destruct(){ $this->close(); }}try { $fp = new writedata('test.txt', 'w'); $fp->write('this is a test'); $fp->close(); echo '数据写入成功!';} catch (fileexception $e) { echo '出问题了:'.$e->getmessage().' 详细信息如下:'.$e->getdetails();}
5.使用观察者模式处理异常 定义观察(异常)的类, 可以在代码中动态的添加观察者 /** * 观察(异常)的类, 可以在代码中动态的添加观察者 */ class observable_exception extends exception { public static $_observers=array(); public static function attach(exception_observer $observer){ self::$_observers[]=$observer; } public function __construct($message=null, $code=0){ parent::__construct($message, $code); $this->notify(); } public function notify(){ foreach (self::$_observers as $observer) { $observer->update($this); } } }
2.定义异常观察者基类,用于规范每一个观察者
/** * 观察者基类,用于规范每一个观察者 */ interface exception_observer{ //强制指定必须是我们规定的观察类 public function update(observable_exception $e); }
3.定义日志观察者
/** * 定义日志观察者 */ class logging_exception_observer implements exception_observer{ public $_filename='./log_exception.log'; public function __construct($filename=null){ if ($filename!==null && is_string($filename)) { $this->_filename=$filename; } } public function update(observable_exception $e){ $message=时间:.date('y-m-d h:i:s').php_eol; $message.=信息:.$e->getmessage().php_eol; $message.=追踪信息:.$e->gettraceasstring().php_eol; $message.=文件:.$e->getfile().php_eol; $message.='行号:'.$e->getline().php_eol; error_log($message, 3, $this->_filename); } }
4.定义邮件观察者
/** * 定义邮件观察者 */ class email_exception_observer implements exception_observer{ public $_email='732578448@qq.com'; public function __construct($email=null){ if ($email!==null && filter_var($email, filter_validate_email)) { $this->_email=$email; } } public function update(observable_exception $e){ $message=时间:.date('y-m-d h:i:s').php_eol; $message.=信息:.$e->getmessage().php_eol; $message.=追踪信息:.$e->gettraceasstring().php_eol; $message.=文件:.$e->getfile().php_eol; $message.='行号:'.$e->getline().php_eol; error_log($message, 1, $this->_email); } }
5.执行测试
error_reporting(-1);ini_set('display_errors','off');//引入观察异常的类require 'observable_exception.php';//引入观察者基类require 'exception_observer.php';//引入日志观察者require 'logging_exception_observer.php';//引入邮件观察者require 'email_exception_observer.php';observable_exception::attach(new logging_exception_observer());//自定义地址记录错误异常observable_exception::attach(new logging_exception_observer('/tmp/test11.log'));observable_exception::attach(new email_exception_observer());//自定义邮件接收人记录错误异常observable_exception::attach(new email_exception_observer('123456@qq.com'));class myexception extends observable_exception{ public function test(){ echo 'this is a test!'; } public function test1(){ echo '我是 自定义的方法处理这个异常!'; }}try { throw new myexception(出现异常了,记录一下下!);} catch (myexception $e) { echo $e->getmessage(); echo ''; $e->test(); echo ''; $e->test1();}
6.自定义异常处理器(set_exception_handler)? 1.目的1处理所有未捕获的异常
2.目的2处理所有我们为放到try catch中的异常
3.自定义异常处理函数 ini_set('display_errors','off');function exceptionhandler_1($e){ echo '自定义异常处理器1'.__function__; echo '异常信息:'.$e->getmessage();}function exceptionhandler_2($e){ echo '自定义异常处理器2'.__function__; echo '异常信息:'.$e->getmessage();}set_exception_handler('exceptionhandler_1');set_exception_handler('exceptionhandler_2');//恢复到上一次定义过的异常处理函数restore_exception_handler();throw new exception('测试');echo 'continue........';echo '';
4.自定义异常处理类 /** * 自定义错误异常类 */class exceptionhandler{ protected $_exception; protected $_logfile='./testexceptionhandler.log'; function __construct(exception $e){ //保存异常对象 $this->_exception = $e; } public static function handle(exception $e){ $self = new self($e); $self->log(); echo $self; } public function log(){ $msg=_exception->gettraceasstring()} 产生通知的行号:{$this->_exception->getline()} 产生通知的错误号:{$this->_exception->getcode()} 产生通知的时间:{$datetime} \n eof; echo $msg; error_log($msg, 3, $this->_logfile); } public function __tostring(){ $message = 2.自定义异常类
class errortoexception extends exception{ public static function handle($errno, $errstr) { throw new self($errstr, $errno); }}ini_set('display_errors', 'off');set_error_handler(array('errortoexception', 'handle'));set_error_handler(array('errortoexception', 'handle'),e_user_warning|e_warning);try { echo $test; gettype(); trigger_error('test',e_user_warning);} catch (exception $e) { echo $e->getmessage();}
8.在发生错误的时候将用户重定向到另一个页面 class exceptionredirecthandler{ protected $_exception; protected $_logfile='./redirectlog.log'; protected $_redirect='404.html'; public function __construct(exception $e){ $this->_exception=$e; } public static function handle(exception $e){ $self = new self($e); $self->log(); while (@ob_end_clean()); header('http/1.1 307 temporary redirect'); header('cache-control:no-cache,must-revalidate'); header('expires: wed, 01 jul 2015 07:40:45 gmt'); header('location:'.$self->_redirect); exit(1); } public function log($value=''){ error_log($this->_exception->getmessage().php_eol, 3, $this->_logfile); }}ini_set('display_errors','off');set_exception_handler(array('exceptionredirecthandler', 'handle'));$link = mysql_connect('localhost', 'brave', '123456123');if (!$link) { throw new exception(数据库受到攻击了,赶快去看看吧!);}
9.设置自定义错误和异常需要传递的参数 异常传递:$msg, $code
错误传递:$errno, $errmsg, $errfile, $errline 可看myerrorhandler.php
版权声明:本文为博主原创文章,未经博主允许不得转载。
其它类似信息

推荐信息