2 /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
10 * @author Tomas V. V. Cox <cox@idecnet.com>
11 * @author Hans Lellelid <hans@velum.net>
12 * @author Bertrand Mansion <bmansion@mamasam.com>
13 * @author Greg Beaver <cellog@php.net>
14 * @copyright 1997-2009 The Authors
15 * @license http://opensource.org/licenses/bsd-license.php New BSD License
16 * @link http://pear.php.net/package/PEAR
17 * @since File available since Release 1.3.3
22 * Base PEAR_Exception Class
26 * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception))
27 * - Definable triggers, shot when exceptions occur
28 * - Pretty and informative error messages
29 * - Added more context info available (like class, method or cause)
30 * - cause can be a PEAR_Exception or an array of mixed
31 * PEAR_Exceptions/PEAR_ErrorStack warnings
32 * - callbacks for specific exception classes and their children
36 * - Maybe a way to define a 'template' for the output
38 * 3) Inherited properties from PHP Exception Class:
46 * 4) Inherited methods from PHP Exception Class:
55 * getTraceSafeAsString
61 * require_once 'PEAR/Exception.php';
65 * throw new PEAR_Exception('Error Message', ERROR_CODE);
69 * function myLogger($pear_exception) {
70 * echo $pear_exception->getMessage();
72 * // each time a exception is thrown the 'myLogger' will be called
73 * // (its use is completely optional)
74 * PEAR_Exception::addObserver('myLogger');
78 * } catch (PEAR_Exception $e) {
85 * @author Tomas V.V.Cox <cox@idecnet.com>
86 * @author Hans Lellelid <hans@velum.net>
87 * @author Bertrand Mansion <bmansion@mamasam.com>
88 * @author Greg Beaver <cellog@php.net>
89 * @copyright 1997-2009 The Authors
90 * @license http://opensource.org/licenses/bsd-license.php New BSD License
91 * @version Release: 1.10.1
92 * @link http://pear.php.net/package/PEAR
93 * @since Class available since Release 1.3.3
96 class PEAR_Exception extends Exception
98 const OBSERVER_PRINT = -2;
99 const OBSERVER_TRIGGER = -4;
100 const OBSERVER_DIE = -8;
102 private static $_observers = array();
103 private static $_uniqueid = 0;
107 * Supported signatures:
108 * - PEAR_Exception(string $message);
109 * - PEAR_Exception(string $message, int $code);
110 * - PEAR_Exception(string $message, Exception $cause);
111 * - PEAR_Exception(string $message, Exception $cause, int $code);
112 * - PEAR_Exception(string $message, PEAR_Error $cause);
113 * - PEAR_Exception(string $message, PEAR_Error $cause, int $code);
114 * - PEAR_Exception(string $message, array $causes);
115 * - PEAR_Exception(string $message, array $causes, int $code);
116 * @param string exception message
117 * @param int|Exception|PEAR_Error|array|null exception cause
118 * @param int|null exception code or null
120 public function __construct($message, $p2 = null, $p3 = null)
125 } elseif (is_object($p2) || is_array($p2)) {
126 // using is_object allows both Exception and PEAR_Error
127 if (is_object($p2) && !($p2 instanceof Exception)) {
128 if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) {
129 throw new PEAR_Exception('exception cause must be Exception, ' .
130 'array, or PEAR_Error');
134 if (is_array($p2) && isset($p2['message'])) {
135 // fix potential problem of passing in a single warning
143 parent::__construct($message, $code);
148 * @param mixed $callback - A valid php callback, see php func is_callable()
149 * - A PEAR_Exception::OBSERVER_* constant
150 * - An array(const PEAR_Exception::OBSERVER_*,
152 * @param string $label The name of the observer. Use this if you want
153 * to remove it later with removeObserver()
155 public static function addObserver($callback, $label = 'default')
157 self::$_observers[$label] = $callback;
160 public static function removeObserver($label = 'default')
162 unset(self::$_observers[$label]);
166 * @return int unique identifier for an observer
168 public static function getUniqueId()
170 return self::$_uniqueid++;
173 private function signal()
175 foreach (self::$_observers as $func) {
176 if (is_callable($func)) {
177 call_user_func($func, $this);
180 settype($func, 'array');
182 case self::OBSERVER_PRINT :
183 $f = (isset($func[1])) ? $func[1] : '%s';
184 printf($f, $this->getMessage());
186 case self::OBSERVER_TRIGGER :
187 $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE;
188 trigger_error($this->getMessage(), $f);
190 case self::OBSERVER_DIE :
191 $f = (isset($func[1])) ? $func[1] : '%s';
192 die(printf($f, $this->getMessage()));
195 trigger_error('invalid observer type', E_USER_WARNING);
201 * Return specific error information that can be used for more detailed
202 * error messages or translation.
204 * This method may be overridden in child exception classes in order
205 * to add functionality not present in PEAR_Exception and is a placeholder
208 * The returned array must be an associative array of parameter => value like so:
210 * array('name' => $name, 'context' => array(...))
214 public function getErrorData()
220 * Returns the exception that caused this exception to be thrown
222 * @return Exception|array The context of the exception
224 public function getCause()
230 * Function must be public to call on caused exceptions
233 public function getCauseMessage(&$causes)
235 $trace = $this->getTraceSafe();
236 $cause = array('class' => get_class($this),
237 'message' => $this->message,
239 'line' => 'unknown');
240 if (isset($trace[0])) {
241 if (isset($trace[0]['file'])) {
242 $cause['file'] = $trace[0]['file'];
243 $cause['line'] = $trace[0]['line'];
247 if ($this->cause instanceof PEAR_Exception) {
248 $this->cause->getCauseMessage($causes);
249 } elseif ($this->cause instanceof Exception) {
250 $causes[] = array('class' => get_class($this->cause),
251 'message' => $this->cause->getMessage(),
252 'file' => $this->cause->getFile(),
253 'line' => $this->cause->getLine());
254 } elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) {
255 $causes[] = array('class' => get_class($this->cause),
256 'message' => $this->cause->getMessage(),
258 'line' => 'unknown');
259 } elseif (is_array($this->cause)) {
260 foreach ($this->cause as $cause) {
261 if ($cause instanceof PEAR_Exception) {
262 $cause->getCauseMessage($causes);
263 } elseif ($cause instanceof Exception) {
264 $causes[] = array('class' => get_class($cause),
265 'message' => $cause->getMessage(),
266 'file' => $cause->getFile(),
267 'line' => $cause->getLine());
268 } elseif (class_exists('PEAR_Error') && $cause instanceof PEAR_Error) {
269 $causes[] = array('class' => get_class($cause),
270 'message' => $cause->getMessage(),
272 'line' => 'unknown');
273 } elseif (is_array($cause) && isset($cause['message'])) {
274 // PEAR_ErrorStack warning
276 'class' => $cause['package'],
277 'message' => $cause['message'],
278 'file' => isset($cause['context']['file']) ?
279 $cause['context']['file'] :
281 'line' => isset($cause['context']['line']) ?
282 $cause['context']['line'] :
290 public function getTraceSafe()
292 if (!isset($this->_trace)) {
293 $this->_trace = $this->getTrace();
294 if (empty($this->_trace)) {
295 $backtrace = debug_backtrace();
296 $this->_trace = array($backtrace[count($backtrace)-1]);
299 return $this->_trace;
302 public function getErrorClass()
304 $trace = $this->getTraceSafe();
305 return $trace[0]['class'];
308 public function getErrorMethod()
310 $trace = $this->getTraceSafe();
311 return $trace[0]['function'];
314 public function __toString()
316 if (isset($_SERVER['REQUEST_URI'])) {
317 return $this->toHtml();
319 return $this->toText();
322 public function toHtml()
324 $trace = $this->getTraceSafe();
326 $this->getCauseMessage($causes);
327 $html = '<table style="border: 1px" cellspacing="0">' . "\n";
328 foreach ($causes as $i => $cause) {
329 $html .= '<tr><td colspan="3" style="background: #ff9999">'
330 . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
331 . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
332 . 'on line <b>' . $cause['line'] . '</b>'
335 $html .= '<tr><td colspan="3" style="background-color: #aaaaaa; text-align: center; font-weight: bold;">Exception trace</td></tr>' . "\n"
336 . '<tr><td style="text-align: center; background: #cccccc; width:20px; font-weight: bold;">#</td>'
337 . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Function</td>'
338 . '<td style="text-align: center; background: #cccccc; font-weight: bold;">Location</td></tr>' . "\n";
340 foreach ($trace as $k => $v) {
341 $html .= '<tr><td style="text-align: center;">' . $k . '</td>'
343 if (!empty($v['class'])) {
344 $html .= $v['class'] . $v['type'];
346 $html .= $v['function'];
348 if (!empty($v['args'])) {
349 foreach ($v['args'] as $arg) {
350 if (is_null($arg)) $args[] = 'null';
351 elseif (is_array($arg)) $args[] = 'Array';
352 elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
353 elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
354 elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
357 $str = htmlspecialchars(substr($arg, 0, 16));
358 if (strlen($arg) > 16) $str .= '…';
359 $args[] = "'" . $str . "'";
363 $html .= '(' . implode(', ',$args) . ')'
365 . '<td>' . (isset($v['file']) ? $v['file'] : 'unknown')
366 . ':' . (isset($v['line']) ? $v['line'] : 'unknown')
367 . '</td></tr>' . "\n";
369 $html .= '<tr><td style="text-align: center;">' . ($k+1) . '</td>'
371 . '<td> </td></tr>' . "\n"
376 public function toText()
379 $this->getCauseMessage($causes);
381 foreach ($causes as $i => $cause) {
382 $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': '
383 . $cause['message'] . ' in ' . $cause['file']
384 . ' on line ' . $cause['line'] . "\n";
386 return $causeMsg . $this->getTraceAsString();