ErrorHandler.php 10 KB

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