ErrorHandler.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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. self::_log($exception, $config);
  111. $renderer = $config['renderer'];
  112. if ($renderer !== 'ExceptionRenderer') {
  113. list($plugin, $renderer) = pluginSplit($renderer, true);
  114. App::uses($renderer, $plugin . 'Error');
  115. }
  116. try {
  117. $error = new $renderer($exception);
  118. $error->render();
  119. } catch (Exception $e) {
  120. set_error_handler(Configure::read('Error.handler')); // Should be using configured ErrorHandler
  121. Configure::write('Error.trace', false); // trace is useless here since it's internal
  122. $message = sprintf("[%s] %s\n%s", // Keeping same message format
  123. get_class($e),
  124. $e->getMessage(),
  125. $e->getTraceAsString()
  126. );
  127. trigger_error($message, E_USER_ERROR);
  128. }
  129. }
  130. /**
  131. * Generates a formatted error message
  132. * @param Exception $exception Exception instance
  133. * @return string Formatted message
  134. */
  135. protected static function _getMessage($exception) {
  136. $message = sprintf("[%s] %s",
  137. get_class($exception),
  138. $exception->getMessage()
  139. );
  140. if (method_exists($exception, 'getAttributes')) {
  141. $attributes = $exception->getAttributes();
  142. if ($attributes) {
  143. $message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
  144. }
  145. }
  146. if (php_sapi_name() !== 'cli') {
  147. $request = Router::getRequest();
  148. if ($request) {
  149. $message .= "\nRequest URL: " . $request->here();
  150. }
  151. }
  152. $message .= "\nStack Trace:\n" . $exception->getTraceAsString();
  153. return $message;
  154. }
  155. /**
  156. * Handles exception logging
  157. *
  158. * @param Exception $exception
  159. * @param array $config
  160. * @return boolean
  161. */
  162. protected static function _log(Exception $exception, $config) {
  163. if (empty($config['log'])) {
  164. return false;
  165. }
  166. if (!empty($config['skipLog'])) {
  167. foreach ((array)$config['skipLog'] as $class) {
  168. if ($exception instanceof $class) {
  169. return false;
  170. }
  171. }
  172. }
  173. return CakeLog::write(LOG_ERR, self::_getMessage($exception));
  174. }
  175. /**
  176. * Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own
  177. * error handling methods. This function will use Debugger to display errors when debug > 0. And
  178. * will log errors to CakeLog, when debug == 0.
  179. *
  180. * You can use Configure::write('Error.level', $value); to set what type of errors will be handled here.
  181. * Stack traces for errors can be enabled with Configure::write('Error.trace', true);
  182. *
  183. * @param integer $code Code of error
  184. * @param string $description Error description
  185. * @param string $file File on which error occurred
  186. * @param integer $line Line that triggered the error
  187. * @param array $context Context
  188. * @return boolean true if error was handled
  189. */
  190. public static function handleError($code, $description, $file = null, $line = null, $context = null) {
  191. if (error_reporting() === 0) {
  192. return false;
  193. }
  194. $errorConfig = Configure::read('Error');
  195. list($error, $log) = self::mapErrorCode($code);
  196. if ($log === LOG_ERR) {
  197. return self::handleFatalError($code, $description, $file, $line);
  198. }
  199. $debug = Configure::read('debug');
  200. if ($debug) {
  201. $data = array(
  202. 'level' => $log,
  203. 'code' => $code,
  204. 'error' => $error,
  205. 'description' => $description,
  206. 'file' => $file,
  207. 'line' => $line,
  208. 'context' => $context,
  209. 'start' => 2,
  210. 'path' => Debugger::trimPath($file)
  211. );
  212. return Debugger::getInstance()->outputError($data);
  213. } else {
  214. $message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  215. if (!empty($errorConfig['trace'])) {
  216. $trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
  217. $message .= "\nTrace:\n" . $trace . "\n";
  218. }
  219. return CakeLog::write($log, $message);
  220. }
  221. }
  222. /**
  223. * Generate an error page when some fatal error happens.
  224. *
  225. * @param integer $code Code of error
  226. * @param string $description Error description
  227. * @param string $file File on which error occurred
  228. * @param integer $line Line that triggered the error
  229. * @return boolean
  230. */
  231. public static function handleFatalError($code, $description, $file, $line) {
  232. $logMessage = 'Fatal Error (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
  233. CakeLog::write(LOG_ERR, $logMessage);
  234. $exceptionHandler = Configure::read('Exception.handler');
  235. if (!is_callable($exceptionHandler)) {
  236. return false;
  237. }
  238. if (ob_get_level()) {
  239. ob_end_clean();
  240. }
  241. if (Configure::read('debug')) {
  242. call_user_func($exceptionHandler, new FatalErrorException($description, 500, $file, $line));
  243. } else {
  244. call_user_func($exceptionHandler, new InternalErrorException());
  245. }
  246. return false;
  247. }
  248. /**
  249. * Map an error code into an Error word, and log location.
  250. *
  251. * @param integer $code Error code to map
  252. * @return array Array of error word, and log location.
  253. */
  254. public static function mapErrorCode($code) {
  255. $error = $log = null;
  256. switch ($code) {
  257. case E_PARSE:
  258. case E_ERROR:
  259. case E_CORE_ERROR:
  260. case E_COMPILE_ERROR:
  261. case E_USER_ERROR:
  262. $error = 'Fatal Error';
  263. $log = LOG_ERR;
  264. break;
  265. case E_WARNING:
  266. case E_USER_WARNING:
  267. case E_COMPILE_WARNING:
  268. case E_RECOVERABLE_ERROR:
  269. $error = 'Warning';
  270. $log = LOG_WARNING;
  271. break;
  272. case E_NOTICE:
  273. case E_USER_NOTICE:
  274. $error = 'Notice';
  275. $log = LOG_NOTICE;
  276. break;
  277. case E_STRICT:
  278. $error = 'Strict';
  279. $log = LOG_NOTICE;
  280. break;
  281. case E_DEPRECATED:
  282. case E_USER_DEPRECATED:
  283. $error = 'Deprecated';
  284. $log = LOG_NOTICE;
  285. break;
  286. }
  287. return array($error, $log);
  288. }
  289. }