_logging_enabled && $code > 2) { $this->_logError(); } } /** * Why not log errors? This could be a base method for doing so. * */ protected function _logError() { /** * See Blog_Exception::getExceptionName() for how to use get_class() * ... and please do not generate timestamps via php for storing in databases :) */ $store_me = array( 'message' => $this->getMessage(), 'file' => $this->getFile(), 'line' => $this->getLine(), 'trace' => $this->getTraceAsString(), 'exception' => get_class($this), 'occurred_at' => date("Y-m-d H:i:s"), 'code' => $this->getCode() ); } /** * Added for demo purposes * * @return Exception */ public function getExceptionName() { return get_class($this); } } /** * Notice how the class declarations acts like descriptions together with php's get_class */ class Blog_Upload_Exception extends Blog_Exception{} class Blog_Comment_Exception extends Blog_Exception{} class Blog_Comment_InvalidHtml_Exception extends Blog_Comment_Exception { protected $_logging_enabled = false; } class Surgeon { public static function continueOperation() { echo "
Yank yank"; } } /** * Example 1: Use of Custom classes * Hit F5 repeatedly to make use of the randomly generated exceptions * Pros: * Good naming convention makes up for possibly simple or abstract message * Easy to extend each class since it is separated * Cons: * Many classes, possibly many files (for example according to the PEAR/Zend convention "1 class/file") */ echo "

Example 1

"; try { $random = mt_rand(1, 3); if($random === 1) { throw new Blog_Upload_Exception('Upload failed', 3); } elseif($random === 2) { throw new Blog_Comment_Exception('Comment failed', 3); } else { throw new Blog_Comment_InvalidHtml_Exception('Unrecognized characters in comment', 3); } } catch (Exception $e) { echo $e->getExceptionName(); if($e->getExceptionName() === 'Blog_Comment_InvalidHtml_Exception') { echo "
That's not too much of an error, I think we should continue this operation anyway"; Surgeon::continueOperation(); } } /** * Example 2: Throw exceptions you can handle */ echo "

Example 2

"; try { try { // Some exceptions are out of your league why not suppress it and throw an exception of your own? throw new UnderflowException; } catch (UnderflowException $e) { throw new Blog_Exception("
Exception caught", 1); } } catch (Blog_Exception $e) { echo $e->getMessage(); } /** * Example 3: Catch more than one type of exception * */ echo "

Example 3

"; class Nuclear_Exception extends Exception {} class Plasma_Exception extends Exception {} try { $random = mt_rand(1, 2); if($random === 1) { throw new Nuclear_Exception('A-bomb alert, be on guard', 4); } else { throw new Plasma_Exception('Aliens are coming, better watch out', 3); } } catch (Nuclear_Exception $e) { echo "
Nuclear missile incoming. Previous transmission: ".$e->getMessage(); } catch (Plasma_Exception $e) { echo "
Alien invasion incoming. Previous transmission: ".$e->getMessage(); }