PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Error/ErrorHandler.php

https://bitbucket.org/projectangelfaces/project-angel-faces
PHP | 283 lines | 135 code | 12 blank | 136 comment | 16 complexity | 42f096cf56ad6455740a7067d839b790 MD5 | raw file
  1. <?php
  2. /**
  3. * Error handler
  4. *
  5. * Provides Error Capturing for Framework errors.
  6. *
  7. * PHP 5
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * For full copyright and license information, please see the LICENSE.txt
  14. * Redistributions of files must retain the above copyright notice.
  15. *
  16. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  17. * @link http://cakephp.org CakePHP(tm) Project
  18. * @package Cake.Error
  19. * @since CakePHP(tm) v 0.10.5.1732
  20. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  21. */
  22. App::uses('Debugger', 'Utility');
  23. App::uses('CakeLog', 'Log');
  24. App::uses('ExceptionRenderer', 'Error');
  25. App::uses('Router', 'Routing');
  26. /**
  27. *
  28. * Error Handler provides basic error and exception handling for your application. It captures and
  29. * handles all unhandled exceptions and errors. Displays helpful framework errors when debug > 1.
  30. *
  31. * ### Uncaught exceptions
  32. *
  33. * When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
  34. * and it is a type that ErrorHandler does not know about it will be treated as a 500 error.
  35. *
  36. * ### Implementing application specific exception handling
  37. *
  38. * You can implement application specific exception handling in one of a few ways. Each approach
  39. * gives you different amounts of control over the exception handling process.
  40. *
  41. * - Set Configure::write('Exception.handler', 'YourClass::yourMethod');
  42. * - Create AppController::appError();
  43. * - Set Configure::write('Exception.renderer', 'YourClass');
  44. *
  45. * #### Create your own Exception handler with `Exception.handler`
  46. *
  47. * This gives you full control over the exception handling process. The class you choose should be
  48. * loaded in your app/Config/bootstrap.php, so its available to handle any exceptions. You can
  49. * define the handler as any callback type. Using Exception.handler overrides all other exception
  50. * handling settings and logic.
  51. *
  52. * #### Using `AppController::appError();`
  53. *
  54. * This controller method is called instead of the default exception rendering. It receives the
  55. * thrown exception as its only argument. You should implement your error handling in that method.
  56. * Using AppController::appError(), will supersede any configuration for Exception.renderer.
  57. *
  58. * #### Using a custom renderer with `Exception.renderer`
  59. *
  60. * If you don't want to take control of the exception handling, but want to change how exceptions are
  61. * rendered you can use `Exception.renderer` to choose a class to render exception pages. By default
  62. * `ExceptionRenderer` is used. Your custom exception renderer class should be placed in app/Lib/Error.
  63. *
  64. * Your custom renderer should expect an exception in its constructor, and implement a render method.
  65. * Failing to do so will cause additional errors.
  66. *
  67. * #### Logging exceptions
  68. *
  69. * Using the built-in exception handling, you can log all the exceptions
  70. * that are dealt with by ErrorHandler by setting `Exception.log` to true in your core.php.
  71. * Enabling this will log every exception to CakeLog and the configured loggers.
  72. *
  73. * ### PHP errors
  74. *
  75. * Error handler also provides the built in features for handling php errors (trigger_error).
  76. * While in debug mode, errors will be output to the screen using debugger. While in production mode,
  77. * errors will be logged to CakeLog. You can control which errors are logged by setting
  78. * `Error.level` in your core.php.
  79. *
  80. * #### Logging errors
  81. *
  82. * When ErrorHandler is used for handling errors, you can enable error logging by setting `Error.log` to true.
  83. * This will log all errors to the configured log handlers.
  84. *
  85. * #### Controlling what errors are logged/displayed
  86. *
  87. * You can control which errors are logged / displayed by ErrorHandler by setting `Error.level`. Setting this
  88. * to one or a combination of a few of the E_* constants will only enable the specified errors.
  89. *
  90. * e.g. `Configure::write('Error.level', E_ALL & ~E_NOTICE);`
  91. *
  92. * Would enable handling for all non Notice errors.
  93. *
  94. * @package Cake.Error
  95. * @see ExceptionRenderer for more information on how to customize exception rendering.
  96. */
  97. class ErrorHandler {
  98. /**
  99. * Set as the default exception handler by the CakePHP bootstrap process.
  100. *
  101. * This will either use custom exception renderer class if configured,
  102. * or use the default ExceptionRenderer.
  103. *
  104. * @param Exception $exception
  105. * @return void
  106. * @see http://php.net/manual/en/function.set-exception-handler.php
  107. */
  108. public static function handleException(Exception $exception) {
  109. $config = Configure::read('Exception');
  110. if (!empty($config['log'])) {
  111. CakeLog::write(LOG_ERR, self::_getMessage($exception));
  112. }
  113. $renderer = isset($config['renderer']) ? $config['renderer'] : 'ExceptionRenderer';
  114. if ($renderer !== 'ExceptionRenderer') {
  115. list($plugin, $renderer) = pluginSplit($renderer, true);
  116. App::uses($renderer, $plugin . 'Error');
  117. }
  118. try {
  119. $error = new $renderer($exception);
  120. $error->render();
  121. } catch (Exception $e) {
  122. set_error_handler(Configure::read('Error.handler')); // Should be using configured ErrorHandler
  123. Configure::write('Error.trace', false); // trace is useless here since it's internal
  124. $message = sprintf("[%s] %s\n%s", // Keeping same message format
  125. get_class($e),
  126. $e->getMessage(),
  127. $e->getTraceAsString()
  128. );
  129. trigger_error($message, E_USER_ERROR);
  130. }
  131. }
  132. /**
  133. * Generates a formatted error message
  134. * @param Exception $exception Exception instance
  135. * @return string Formatted message
  136. */
  137. protected static function _getMessage($exception) {
  138. $message = sprintf("[%s] %s",
  139. get_class($exception),
  140. $exception->getMessage()
  141. );
  142. if (method_exists($exception, 'getAttributes')) {
  143. $attributes = $exception->getAttributes();
  144. if ($attributes) {
  145. $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
  146. }
  147. }
  148. if (php_sapi_name() !== 'cli') {
  149. $request = Router::getRequest();
  150. if ($request) {
  151. $message .= "\nRequest URL: " . $request->here();
  152. }
  153. }
  154. $message .= "\nStack Trace:\n" . $exception->getTraceAsString();
  155. return $message;
  156. }
  157. /**
  158. * Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own
  159. * error handling methods. This function will use Debugger to display errors when debug > 0. And
  160. * will log errors to CakeLog, when debug == 0.
  161. *
  162. * You can use Configure::write('Error.level', $value); to set what type of errors will be handled here.
  163. * Stack traces for errors can be enabled with Configure::write('Error.trace', true);
  164. *
  165. * @param integer $code Code of error
  166. * @param string $description Error description
  167. * @param string $file File on which error occurred
  168. * @param integer $line Line that triggered the error
  169. * @param array $context Context
  170. * @return boolean true if error was handled
  171. */
  172. public static function handleError($code, $description, $file = null, $line = null, $context = null) {
  173. if (error_reporting() === 0) {
  174. return false;
  175. }
  176. $errorConfig = Configure::read('Error');
  177. list($error, $log) = self::mapErrorCode($code);
  178. if ($log === LOG_ERR) {
  179. return self::handleFatalError($code, $description, $file, $line);
  180. }
  181. $debug = Configure::read('debug');
  182. if ($debug) {
  183. $data = array(
  184. 'level' => $log,
  185. 'code' => $code,
  186. 'error' => $error,
  187. 'description' => $description,
  188. 'file' => $file,
  189. 'line' => $line,
  190. 'context' => $context,
  191. 'start' => 2,
  192. 'path' => Debugger::trimPath($file)
  193. );
  194. return Debugger::getInstance()->outputError($data);
  195. } else {
  196. $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  197. if (!empty($errorConfig['trace'])) {
  198. $trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
  199. $message .= "\nTrace:\n" . $trace . "\n";
  200. }
  201. return CakeLog::write($log, $message);
  202. }
  203. }
  204. /**
  205. * Generate an error page when some fatal error happens.
  206. *
  207. * @param integer $code Code of error
  208. * @param string $description Error description
  209. * @param string $file File on which error occurred
  210. * @param integer $line Line that triggered the error
  211. * @return boolean
  212. */
  213. public static function handleFatalError($code, $description, $file, $line) {
  214. $logMessage = 'Fatal Error (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  215. CakeLog::write(LOG_ERR, $logMessage);
  216. $exceptionHandler = Configure::read('Exception.handler');
  217. if (!is_callable($exceptionHandler)) {
  218. return false;
  219. }
  220. if (ob_get_level()) {
  221. ob_end_clean();
  222. }
  223. if (Configure::read('debug')) {
  224. call_user_func($exceptionHandler, new FatalErrorException($description, 500, $file, $line));
  225. } else {
  226. call_user_func($exceptionHandler, new InternalErrorException());
  227. }
  228. return false;
  229. }
  230. /**
  231. * Map an error code into an Error word, and log location.
  232. *
  233. * @param integer $code Error code to map
  234. * @return array Array of error word, and log location.
  235. */
  236. public static function mapErrorCode($code) {
  237. $error = $log = null;
  238. switch ($code) {
  239. case E_PARSE:
  240. case E_ERROR:
  241. case E_CORE_ERROR:
  242. case E_COMPILE_ERROR:
  243. case E_USER_ERROR:
  244. $error = 'Fatal Error';
  245. $log = LOG_ERR;
  246. break;
  247. case E_WARNING:
  248. case E_USER_WARNING:
  249. case E_COMPILE_WARNING:
  250. case E_RECOVERABLE_ERROR:
  251. $error = 'Warning';
  252. $log = LOG_WARNING;
  253. break;
  254. case E_NOTICE:
  255. case E_USER_NOTICE:
  256. $error = 'Notice';
  257. $log = LOG_NOTICE;
  258. break;
  259. case E_STRICT:
  260. $error = 'Strict';
  261. $log = LOG_NOTICE;
  262. break;
  263. case E_DEPRECATED:
  264. case E_USER_DEPRECATED:
  265. $error = 'Deprecated';
  266. $log = LOG_NOTICE;
  267. break;
  268. }
  269. return array($error, $log);
  270. }
  271. }