位置:PHP教程 > PHP源码

php异常处理类代码

时间:2013-12-30
简介:PHP教程|这个类可以用来处理PHP的执行错误和异常。它可以注册回调函数来处理致命性和非致命错误,以及未捕获的异常。这个类还可以设置选项来输出调试信息和调用时的错误和异常发
这个类可以 用来处理 PHP的 执行错误 和异常。

可以注册 回调 函数来处理 致命性和 非致命错误 ,以及 未捕获的异常

这个类还可以设置选项来输出调试信息和调用的错误和异常发生的错误处理回调函数。

<?php
/*

include 'debug.class.php';

function e_callback($e) {
	// could write to log, send email, redirect
	//print $e;
	//header('Location: error.html');
}

All settings have defaults include the class set only the ones you want to change
debug::settings(array(
	'error_exception_class' => '',
	'display_switch' => TRUE,
	'display_errors' => TRUE,
	'display_dump' => TRUE,
	'catch_errors' => TRUE,
	'php_display_errors' => FALSE,
	'php_error_reporting' => -1,
	'error_handler_callback' => 'e_callback',
	'exception_handler_callback' => 'e_callback',
	'fatal_error_handler_callback' => 'e_callback',
	'display_exceptions' => TRUE,
	'catch_exceptions' => TRUE,
	
	));

$t = $y // with cause undefined variable

*/

// debug function, quick dump access
function debug($var) {
	debug::dump($var);
}

abstract class debug {

	const TYPE_DUMP = 1;
	const TYPE_ERROR = 2;
	const TYPE_EXCEPTION = 3;
	
	// Any output collected will be stored here even when not displaying
	protected static $output = '';

	// Custom classes to use for errors
	protected static $error_exception_class = '';
	
	// when set to true errors will be printed out
	// The Main Switch, if this is false nothing will get sent out
	protected static $display_switch = FALSE;
	
	// Show or Hide  
	protected static $display_errors = FALSE;
	protected static $display_dump = FALSE;
	protected static $display_exceptions = FALSE;
	
	// Catch Errors , Exceptions?
	protected static $catch_errors = FALSE;
	protected static $catch_exceptions = FALSE;
	

	/* The callback to use when an error / exception is caught
	 * Exception will be passed along. This callback function could be used
	 * to email, write to log, redirect to a 'nicely formated error page'
	 */
	protected static $error_handler_callback = '';
	protected static $exception_handler_callback = '';
	protected static $fatal_error_handler_callback = '';
	
	// PHP'S display errors
	protected static $php_display_errors = TRUE;
	
	// PHP's error reporting
	protected static $php_error_reporting = -1;
	
	// Dump a Var, regular function debug($var) can be used
	public static function dump($var) {
		$rtrn = var_export($var,true);
		self::output( $rtrn , self::TYPE_DUMP);
	}
	
	// Init with settings. we are just setting the public properties,
	// so no error checking is done. This is just a batch settings handler
	// and an Init function
	public static function settings(array $settings = array()) {
		
		// set the settings
		foreach($settings as $property => $option) {
			$method = 'set_'.$property;
			if(method_exists(__CLASS__,$method)) {
				self::$method($option);
			}
		}
	}
	/**
	 * Get Methods
	 */
	// return any output collected
	public static function get_output() {
		return self::$output;
	}
	
	/**
	 * Set Methods
	 */
	public static function set_fatal_error_handler_callback($option) {
		self::$fatal_error_handler_callback = $option;
	}
	public static function set_exception_handler_callback($option) {
		self::$exception_handler_callback = $option;
	}
	public static function set_error_handler_callback($option) {
		self::$error_handler_callback = $option;
	}
	public static function set_error_exception_class($option) {
		self::$error_exception_class = $option;
	}
	public static function set_display_switch($option) {
		if(is_bool($option)) {
			self::$display_switch = $option;
		}
	}
	public static function set_display_errors($option) {
		if(is_bool($option)) {
			self::$display_errors = $option;
		}
	}
	public static function set_display_exceptions($option){
		if(is_bool($option)) {
			self::$display_exceptions = $option;
		}
	}
	/*
	 * Enable / Disable printing var dumps
	 * 
	 * void set_display_dump( bool $option )
	 * 
	 */
	public static function set_display_dump($option) {
		if(is_bool($option)) {
			self::$display_dump = $option;
		}
	}
	
	/*
	 * Enable / Disable catching of uncaught exceptions
	 * 
	 * void set_catch_exceptions( bool $option )
	 * 
	 */
	public static function set_catch_exceptions($option) {
		if(is_bool($option)) {
			// if settings TRUE and option FALSE
			if(self::$catch_exceptions === TRUE && $option === FALSE) {
				restore_exception_handler();
			
			// if settings FALSE and option TRUE
			} elseif(self::$catch_exceptions === FALSE && $option === TRUE) {
				set_exception_handler('debug::catch_exception');
			}
			self::$catch_exceptions = $option;
		}
	}
	
	/*
	 * Enable / Disable catching of errors
	 * 
	 * void set_catch_errors( bool $option )
	 * 
	 */
	public static function set_catch_errors($option) {
		if(is_bool($option)) {
			// if settings TRUE and option FALSE
			if(self::$catch_errors === TRUE && $option === FALSE) {
				restore_error_handler();
			
			// if settings FALSE and option TRUE
			} elseif(self::$catch_errors === FALSE && $option === TRUE) {
				set_error_handler('debug::catch_error');
				register_shutdown_function('debug::catch_fatal_error');
			}
			self::$catch_errors = $option;
		}
	}
	/*
	 * Set PHP's Error Reporting settings
	 * 
	 * void set_php_error_reporting($new_error_level=null)
	 * 
	 */
	public static function set_php_error_reporting($new_error_level=null) {
		if(isset($new_error_level)) {
			// save the option
			self::$php_error_reporting = $new_error_level;
		}
		// set the option
		return error_reporting($new_error_level);
	}
	/*
	 * Set PHP's Display Errors Setting
	 * 
	 * void set_php_display_errors($option = -1)
	 * 
	 */
	public static function set_php_display_errors($option = -1) {
		
		// save the option
		self::$php_display_errors = $option;
		
		// Set PHP display errors with debug settings
		ini_set("display_errors", self::$php_display_errors);
	}
	
	/*
	 * Check if there any fatal errors.
	 * If php is not displaying errors these will not be displayed.
	 * 
	 * void catch_fatal_error( void )
	 *
	 */
	public static function catch_fatal_error() {
		$error = error_get_last();

		if( $error !== NULL) {
			$errno   = $error["type"];
			$err_file = $error["file"];
			$err_line = $error["line"];
			$err_str  = $error["message"];
					
			// Output the Fatal Error
			//$e = new FatalException($err_str, 0, $errno, $err_file, $err_line);
			self::catch_error($errno, $err_str, $err_file, $err_line, array());
			//self::output($e,self::TYPE_ERROR);
			//self::output($errno,self::TYPE_ERROR);
			// Attempt the callback
			//self::callback(self::$fatal_error_handler_callback,$e);
		}
	}
	/*
	 * Handle uncaught Exceptions.  Exceptions will stop a script from continuing. Any code after
	 * the exception will not execute. Any last min. things can be handled in the callback function
	 * 
	 * void catch_exception( exception $e )
	 *
	 */
	public static function catch_exception($e) {
			
		// Output the Error Exception
		self::output($e,self::TYPE_EXCEPTION);
		
		// Attempt the callback
		self::callback(self::$exception_handler_callback,$e);

	}
	
	/*
	 * Handle caught errors.
	 * A custom error exception class can be set for flexibilty.
	 * If the class doesnt exist, ErrorException is used
	 * 
	 * void catch_error($err_severity, $err_msg, $err_file, $err_line, array $err_context)
	 * 
	 */
	 /*
	  * 1    		E_ERROR (integer)     Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted.     
	  * 2    		E_WARNING (integer)     Run-time warnings (non-fatal errors). Execution of the script is not halted.     
	  * 4    		E_PARSE (integer)     Compile-time parse errors. Parse errors should only be generated by the parser.     
	  * 8    		E_NOTICE (integer)     Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.     
	  * 16    		E_CORE_ERROR (integer)     Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP.     
	  * 32    		E_CORE_WARNING (integer)     Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP.     
	  * 64    		E_COMPILE_ERROR (integer)     Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine.     
	  * 128    		E_COMPILE_WARNING (integer)     Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine.     
	  * 256    		E_USER_ERROR (integer)     User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error().     
	  * 512    		E_USER_WARNING (integer)     User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error().     
	  * 1024    	E_USER_NOTICE (integer)     User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error().     
	  * 2048    	E_STRICT (integer)     Enable to have PHP suggest changes to your code which will ensure the best interoperability and forward compatibility of your code.    Since PHP 5 but not included in E_ALL until PHP 5.4.0
	  * 4096    	E_RECOVERABLE_ERROR (integer)     Catchable fatal error. It indicates that a probably dangerous error occurred, but did not leave the Engine in an unstable state. If the error is not caught by a user defined handle (see also set_error_handler()), the application aborts as it was an E_ERROR.    Since PHP 5.2.0
	  * 8192    	E_DEPRECATED (integer)     Run-time notices. Enable this to receive warnings about code that will not work in future versions.    Since PHP 5.3.0
	  * 16384    	E_USER_DEPRECATED (integer)     User-generated warning message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error().    Since PHP 5.3.0
	  * 32767    	E_ALL
*/
	public static function catch_error($err_severity, $err_msg, $err_file, $err_line, array $err_context) {
		/*
		echo 'severity='.$err_severity.'</br>';
		echo 'notice='.E_USER_NOTICE.'</br>';
		echo 'WARNING='.E_USER_WARNING.'</br>';
		echo 'ERROR='.E_USER_ERROR.'</br>';
		*/
		switch($err_severity)
		{
			case E_ERROR:               $e = new ErrorException            ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_WARNING:             $e = new WarningException          ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_PARSE:               $e = new ParseException            ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_NOTICE:              $e = new NoticeException           ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_CORE_ERROR:          $e = new CoreErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_CORE_WARNING:        $e = new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_COMPILE_ERROR:       $e = new CompileErrorException     ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_COMPILE_WARNING:     $e = new CoreWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_USER_ERROR:          $e = new UserErrorException        ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_USER_WARNING:        $e = new UserWarningException      ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_USER_NOTICE:         $e = new UserNoticeException       ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_STRICT:              $e = new StrictException           ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_RECOVERABLE_ERROR:   $e = new RecoverableErrorException ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_DEPRECATED:          $e = new DeprecatedException       ($err_msg, 0, $err_severity, $err_file, $err_line); break;
			case E_USER_DEPRECATED:     $e = new UserDeprecatedException   ($err_msg, 0, $err_severity, $err_file, $err_line); break;
		}
		
		// Output the Error Exception
		self::output($e,self::TYPE_ERROR);	
		
		// Attempt the callback
		self::callback(self::$error_handler_callback,$e);

	}
	
	/*
	 * Output Handler. Collect / Store. Display depending on settings
	 * 
	 * void output( string $output, int $type )
	 * 
	 */
	protected static function output($output,$type) {
		$output = '<pre>' . $output . '</pre>';
		self::$output .= $output;
		if(self::$display_switch) {
			if($type == self::TYPE_DUMP && self::$display_dump) {
				echo $output;
			} elseif($type == self::TYPE_ERROR && self::$display_errors) {
				echo $output;
			} elseif($type == self::TYPE_EXCEPTION && self::$display_exceptions) {
				echo $output;
			}
		}
	}
	/*
	 * Call the callback
	 * 
	 * void callback( string $callback, mixed $arg )
	 * 
	 */
	protected static function callback($callback,$arg) {
		if(is_callable($callback)) {
			call_user_func($callback,$arg);
		}
	}
}

class FatalException extends ErrorException  {}


class WarningException              extends ErrorException {}
class ParseException                extends ErrorException {}
class NoticeException               extends ErrorException {}
class CoreErrorException            extends ErrorException {}
class CoreWarningException          extends ErrorException {}
class CompileErrorException         extends ErrorException {}
class CompileWarningException       extends ErrorException {}
class UserErrorException            extends ErrorException {}
class UserWarningException          extends ErrorException {}
class UserNoticeException           extends ErrorException {}
class StrictException               extends ErrorException {}
class RecoverableErrorException     extends ErrorException {}
class DeprecatedException           extends ErrorException {}
class UserDeprecatedException       extends ErrorException {}

TAGS:php异常处理类

上一编:PHP取得某年某月的天数

下一编:用php或js获取图片大小,高宽尺寸的代码

NewHot手机版