ErrorHandler.php 5.7 KB

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