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

/lib/Cake/Error/ErrorHandler.php

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