Exception handling in PHP 1. what is an exception? What is the difference between an exception and an error?
1. exception: The program runs differently than expected. There are two different concepts!
2. throw and capture exceptions
3. when there are multiple catch blocks, the base class should be put back. Otherwise, the base class will not continue to catch exceptions!
3. an error occurs first and an exception occurs. Therefore, you must disable display_errors when writing APIs.
4. php built-in exceptions
Error_reporting (-1); ini_set ('display _ errors ', 'off'); // pdo built-in exception class try {$ pdo = new PDO ('MySQL: host = localhost; dbname = mysql ', 'Brave', '123'); var_dump ($ pdo); echo'
'; Echo 'continue ....... ';} catch (Exception $ e) {echo $ e-> getMessage ();} echo' this is a test ....... '; echo'
'; // Spl file read/write built-in exception class try {$ splObj = new SplFileObject('test.txt', 'r'); echo 'read file';} catch (RuntimeException $ e) {echo $ e-> getMessage ();} echo 'continue ....... '; echo'
';2. basic syntax structure of exceptions
Try {// code throw for Exception handling} catch (PdoException $ e) {try {throw statement throw} catch (Exception $ e) {}} catch (FileException $ e) {} catch (CustomException $ e) {}// other code3. how to customize exception classes?
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 = "An exception occurred. The information is as follows"; $ message. ="". _ CLASS _." [{$ this-> code}]: {$ this-> message}
"; Return $ message;} public function test () {echo 'This is a test';} public function stop () {exit ('script end ..............
');} // Other custom methods} try {echo' exception! '; Throw new MyException ("test custom exception! ", 11);} catch (MyException $ e) {echo $ e-> getMessage (); echo'
'; Echo $ e; echo'
'; $ E-> stop (); $ e-> test ();}4. Custom file exception class
Error_reporting (-1); ini_set ('display _ errors ', 'off'); class FileException extends Exception {public function getDetails () {switch ($ this-> code) {case 0: return 'no file provided! '; Break; case 1: return' file does not exist! '. "Trace". $ this-> getTraceAsString (). $ this-> getLine (); break; case 2: return' is not a file! '. "Trace". $ this-> getTraceAsString (). $ this-> getLine (); break; case 3: return' the file cannot be written! '; Break; case 4: return' Illegal File operation mode! '; Break; case 5: return' data writing failed! '; Break; case 6: return' file cannot be closed! '; Break; default: return' is invalid! '; Break ;}} class WriteData {private $ _ message = ''; private $ _ fp = null; public function _ construct ($ filename = null, $ mode = 'w') {$ this-> _ message = "file: {$ filename} mode: {$ 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 data] * @ 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 the file handle] * @ 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 'data written successfully! ';} Catch (FileException $ e) {echo :'. $ e-> getMessage (). 'detailed information :'. $ e-> getDetails ();}5. handle exceptions in Observer Mode
- Defines the observed (abnormal) class. you can dynamically add the observer in the code.
/*** Observed (abnormal) class. you can dynamically add the observer */class Observable_Exception extends Exception {public static $ _ observers = array () in the code (); public static function attach (Exception_Observer $ observer) {self ::: _ observers [] = $ observer;} public function _ construct ($ message = null, $ code = 0) {parent ::__ construct ($ message, $ code); $ this-> using Y ();} public function using Y () {foreach (self :: $ _ observers as $ observer) {$ observer-> update ($ this );}}}
2. define abnormal ObserverBase ClassTo regulate every observer
/*** Observer base class, which is used to standardize every observer */interface Exception_Observer {// forcibly specify that the observation class must be public function update (Observable_Exception $ e );}
3. define the log Observer
/*** Define the log observer */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 = "time: ". date ('Y-m-d H: I: s '). PHP_EOL; $ message. = "information :". $ e-> getMessage (). PHP_EOL; $ message. = "tracing information :". $ e-> getTraceAsString (). PHP_EOL; $ message. = "file :". $ e-> getFile (). PHP_EOL; $ message. = 'line number :'. $ e-> getLine (). PHP_EOL; error_log ($ message, 3, $ this-> _ filename );}}
4. define email Observer
/*** Define email observer */class Email_Exception_Observer implements Exception_Observer {public $ _ email = '2017 @ 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 = "time :". date ('Y-m-d H: I: s '). PHP_EOL; $ message. = "information :". $ e-> getMessage (). PHP_EOL; $ message. = "tracing information :". $ e-> getTraceAsString (). PHP_EOL; $ message. = "file :". $ e-> getFile (). PHP_EOL; $ message. = 'line number :'. $ e-> getLine (). PHP_EOL; error_log ($ message, 1, $ this-> _ email );}}
5. run the test.
Error_reporting (-1); ini_set ('display _ errors ', 'off'); // introduces the require 'observable _ Exception class to observe exceptions. php'; // introduce the Observer base class require 'exception _ Observer. php '; // introduce the log observer require 'logging _ Exception_Observer.php'; // introduce the Email observer require 'email _ Exception_Observer.php '; Observable_Exception: attach (new Logging_Exception_Observer ()); // error Observable_Exception: attach (new Logging_Exception_Observer ('/tmp/test11.log'); Observab Le_Exception: attach (new Email_Exception_Observer (); // custom email recipient record error exception Observable_Exception: attach (new Email_Exception_Observer ('2017 @ qq.com ')); class MyException extends Observable_Exception {public function test () {echo 'This is a test! ';} Public function test1 () {echo' I am a custom method to handle this exception! ';} Try {throw new MyException ("An exception occurred. record the exception! ");} Catch (MyException $ e) {echo $ e-> getMessage (); echo'
'; $ E-> test (); echo'
'; $ E-> test1 ();}6. Custom exception processor (set_exception_handler )?
1. Objective 1 handle all uncaptured exceptions
2. Objective 2: to handle all exceptions that we put into try catch
3. Custom exception handling functions
Ini_set ('display _ errors ', 'off'); function exceptionHandler_1 ($ e) {echo 'custom exception processor 1 '. _ FUNCTION __; echo 'exception information :'. $ e-> getMessage ();} function exceptionHandler_2 ($ e) {echo 'custom exception processor 2 '. _ FUNCTION __; echo 'exception information :'. $ e-> getMessage ();} set_exception_handler ('exceptionhandler _ 1'); set_exception_handler ('exceptionhandler _ 2 '); // restore to the previously defined Exception handling function restore_exception_handler (); throw new Exception ('test'); echo 'continue ........ '; echo'
';4. Custom exception handling class
/*** Custom error exception class */class ExceptionHandler {protected $ _ exception; protected $ _ logFile = '. /testExceptionHandler. log'; function _ construct (Exception $ e) {// Save the exception object $ this-> _ Exception = $ e;} public static function handle (Exception $ e) {$ self = new self ($ e); $ self-> log (); echo $ self;} public function log () {$ msg = <
_ Exception-> getFile ()}
Notification generation Information: {$ this-> _ exception-> getTraceAsString ()} the row number of the notification: {$ this-> _ exception-> getLine ()} error code: {$ this-> _ exception-> getCode ()} time when the notification was generated: {$ datetime} \ n EOF; echo $ msg; error_log ($ msg, 3, $ this-> _ logFile);} public function _ toString () {$ message = <
An exception occurred .....
Refresh
EOF; return $ message ;}} ini_set ('display _ errors ', 'off'); set_exception_handler (array ('exceptionhandler', 'handle ')); // put the throwtry {throw new Exception ("this is a test! ", 20010);} catch (Exception $ e) {echo $ e-> getMessage ();} // throwthrow new Exception that is not put in try catch ("test the uncaptured custom Exception processor hello world! ", 2008 );
7. how to handle PHP errors like handling exceptions?
1. ErrorException
function exception_error_handler($errno, $errstr, $errfile, $errline){ throw new ErrorException($errstr, 0, $errno, $errfile, $errline);}set_error_handler('exception_error_handler');try { echo gettype();} catch (Exception $e) { echo $e->getMessage();}
2. Custom exception classes
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. redirect the user to another page when an error occurs.
Class ExceptionRedirectHandler {protected $ _ exception; protected $ _ logFile = '. /redirectLog. log'; protected pai_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 redirection '); 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 ', '123'); if (! $ Link) {throw new Exception ("The database is under attack. Please check it out! ");}9. set parameters to be passed for custom errors and exceptions
Exception transfer: $ msg, $ code
Error message: $ errno, $ errmsg, $ errfile, $ errline can be seen in MyErrorHandler. php
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.