ErrorHandler.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. /**
  3. * ErrorHandler class
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  13. * @link https://cakephp.org CakePHP(tm) Project
  14. * @since 0.10.5
  15. * @license https://opensource.org/licenses/mit-license.php MIT License
  16. */
  17. namespace Cake\Error;
  18. use Cake\Core\App;
  19. use Cake\Http\ResponseEmitter;
  20. use Exception;
  21. use Throwable;
  22. /**
  23. * Error Handler provides basic error and exception handling for your application. It captures and
  24. * handles all unhandled exceptions and errors. Displays helpful framework errors when debug mode is on.
  25. *
  26. * ### Uncaught exceptions
  27. *
  28. * When debug mode is off a ExceptionRenderer will render 404 or 500 errors. If an uncaught exception is thrown
  29. * and it is a type that ExceptionRenderer does not know about it will be treated as a 500 error.
  30. *
  31. * ### Implementing application specific exception handling
  32. *
  33. * You can implement application specific exception handling in one of a few ways. Each approach
  34. * gives you different amounts of control over the exception handling process.
  35. *
  36. * - Modify config/error.php and setup custom exception handling.
  37. * - Use the `exceptionRenderer` option to inject an Exception renderer. This will
  38. * let you keep the existing handling logic but override the rendering logic.
  39. *
  40. * #### Create your own Exception handler
  41. *
  42. * This gives you full control over the exception handling process. The class you choose should be
  43. * loaded in your config/error.php and registered as the default exception handler.
  44. *
  45. * #### Using a custom renderer with `exceptionRenderer`
  46. *
  47. * If you don't want to take control of the exception handling, but want to change how exceptions are
  48. * rendered you can use `exceptionRenderer` option to choose a class to render exception pages. By default
  49. * `Cake\Error\ExceptionRenderer` is used. Your custom exception renderer class should be placed in src/Error.
  50. *
  51. * Your custom renderer should expect an exception in its constructor, and implement a render method.
  52. * Failing to do so will cause additional errors.
  53. *
  54. * #### Logging exceptions
  55. *
  56. * Using the built-in exception handling, you can log all the exceptions
  57. * that are dealt with by ErrorHandler by setting `log` option to true in your config/error.php.
  58. * Enabling this will log every exception to Log and the configured loggers.
  59. *
  60. * ### PHP errors
  61. *
  62. * Error handler also provides the built in features for handling php errors (trigger_error).
  63. * While in debug mode, errors will be output to the screen using debugger. While in production mode,
  64. * errors will be logged to Log. You can control which errors are logged by setting
  65. * `errorLevel` option in config/error.php.
  66. *
  67. * #### Logging errors
  68. *
  69. * When ErrorHandler is used for handling errors, you can enable error logging by setting the `log`
  70. * option to true. This will log all errors to the configured log handlers.
  71. *
  72. * #### Controlling what errors are logged/displayed
  73. *
  74. * You can control which errors are logged / displayed by ErrorHandler by setting `errorLevel`. Setting this
  75. * to one or a combination of a few of the E_* constants will only enable the specified errors:
  76. *
  77. * ```
  78. * $options['errorLevel'] = E_ALL & ~E_NOTICE;
  79. * ```
  80. *
  81. * Would enable handling for all non Notice errors.
  82. *
  83. * @see \Cake\Error\ExceptionRenderer for more information on how to customize exception rendering.
  84. */
  85. class ErrorHandler extends BaseErrorHandler
  86. {
  87. /**
  88. * Constructor
  89. *
  90. * @param array $options The options for error handling.
  91. */
  92. public function __construct($options = [])
  93. {
  94. $defaults = [
  95. 'log' => true,
  96. 'trace' => false,
  97. 'exceptionRenderer' => ExceptionRenderer::class,
  98. ];
  99. $this->_options = $options + $defaults;
  100. }
  101. /**
  102. * Display an error.
  103. *
  104. * Template method of BaseErrorHandler.
  105. *
  106. * @param array $error An array of error data.
  107. * @param bool $debug Whether or not the app is in debug mode.
  108. * @return void
  109. */
  110. protected function _displayError($error, $debug)
  111. {
  112. if (!$debug) {
  113. return;
  114. }
  115. Debugger::getInstance()->outputError($error);
  116. }
  117. /**
  118. * Displays an exception response body.
  119. *
  120. * @param \Exception $exception The exception to display.
  121. * @return void
  122. * @throws \Exception When the chosen exception renderer is invalid.
  123. */
  124. protected function _displayException($exception)
  125. {
  126. $rendererClassName = App::className($this->_options['exceptionRenderer'], 'Error');
  127. try {
  128. if (!$rendererClassName) {
  129. throw new Exception("$rendererClassName is an invalid class.");
  130. }
  131. /** @var \Cake\Error\ExceptionRendererInterface $renderer */
  132. $renderer = new $rendererClassName($exception);
  133. $response = $renderer->render();
  134. $this->_clearOutput();
  135. $this->_sendResponse($response);
  136. } catch (Throwable $exception) {
  137. $this->_logInternalError($exception);
  138. } catch (Exception $exception) {
  139. $this->_logInternalError($exception);
  140. }
  141. }
  142. /**
  143. * Clear output buffers so error pages display properly.
  144. *
  145. * Easily stubbed in testing.
  146. *
  147. * @return void
  148. */
  149. protected function _clearOutput()
  150. {
  151. while (ob_get_level()) {
  152. ob_end_clean();
  153. }
  154. }
  155. /**
  156. * Logs both PHP5 and PHP7 errors.
  157. *
  158. * The PHP5 part will be removed with 4.0.
  159. *
  160. * @param \Throwable|\Exception $exception Exception.
  161. *
  162. * @return void
  163. */
  164. protected function _logInternalError($exception)
  165. {
  166. // Disable trace for internal errors.
  167. $this->_options['trace'] = false;
  168. $message = sprintf(
  169. "[%s] %s (%s:%s)\n%s", // Keeping same message format
  170. get_class($exception),
  171. $exception->getMessage(),
  172. $exception->getFile(),
  173. $exception->getLine(),
  174. $exception->getTraceAsString()
  175. );
  176. trigger_error($message, E_USER_ERROR);
  177. }
  178. /**
  179. * Method that can be easily stubbed in testing.
  180. *
  181. * @param string|\Cake\Http\Response $response Either the message or response object.
  182. * @return void
  183. */
  184. protected function _sendResponse($response)
  185. {
  186. if (is_string($response)) {
  187. echo $response;
  188. return;
  189. }
  190. $emitter = new ResponseEmitter();
  191. $emitter->emit($response);
  192. }
  193. }