Home  >  Article  >  php教程  >  thinkphp 异常处理机制

thinkphp 异常处理机制

WBOY
WBOYOriginal
2016-06-06 19:33:031075browse

说明: 1.扔出的异常(throwexception)如果没有被对应的catch块捕获,则会传递到顶级的异常处理器(如果设置了的话) 2.异常的对象的getTrace()方法可以跟踪是异常是在哪个函数中抛出的 3.我们要处理的异常信息一般有四个:异常信息(getMessage)、文件位置(getFile

说明: 
   1.扔出的异常(throw exception)如果没有被对应的catch块捕获,则会传递到顶级的异常处理器(如果设置了的话)
   2.异常的对象的getTrace()方法可以跟踪是异常是在哪个函数中抛出的
   3.我们要处理的异常信息一般有四个: 异常信息(getMessage)、文件位置(getFile)、所在的行(getLine)、trace信息(debug_print_backtrace)
   4.thinkphp 只有通过两种方式扔出异常: 1.直接扔出(throw new Excepiton) 2.通过函数 throw_exception() 扔出
   5.异常扔出后,会找catch块或顶级异常处理器,其他代码不会执行了
<?php
	//设置顶级异常处理器
	set_exception_handler(array('Think','appException'));
	class Think{
			static public function appException($e){
					$error['message'] = $e->getMessage();
					$trace = $e->getTrace();
					//如果通过throw_exception扔出则定位到throw_exception被调用的位置
					if($trace[0]['function'] == 'throw_exception'){
						$error['file'] = $trace[0]['file'];
						$error['line'] = $trace[0]['line'];
					}else{
						//直接扔出异常
						$error['file'] = $e->getFile();
						$error['line'] = $e->getLine();
					}
					//调试信息
					//$error['trace'] = debug_print_backtrace();
					//调用异常模板输出即可
					//include C('TEMP_EXCEPTION_FILE');
					print_r($error);
			}
	}

	function throw_exception($message){
			 throw new Exception($message);
	}	
	throw_exception('在throw_exception函数扔出的异常!,会定位到throw_exception调用的位置');
thinkphp 异常处理机制
Statement:
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