ErrorHandler.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. use yii\helpers\VarDumper;
  10. use yii\web\HttpException;
  11. /**
  12. * ErrorHandler handles uncaught PHP errors and exceptions.
  13. *
  14. * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
  15. * You can access that instance via `Yii::$app->errorHandler`.
  16. *
  17. * For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @author Alexander Makarov <sam@rmcreative.ru>
  21. * @author Carsten Brandt <mail@cebe.cc>
  22. * @since 2.0
  23. */
  24. abstract class ErrorHandler extends Component
  25. {
  26. /**
  27. * @var bool whether to discard any existing page output before error display. Defaults to true.
  28. */
  29. public $discardExistingOutput = true;
  30. /**
  31. * @var int the size of the reserved memory. A portion of memory is pre-allocated so that
  32. * when an out-of-memory issue occurs, the error handler is able to handle the error with
  33. * the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
  34. * Defaults to 256KB.
  35. */
  36. public $memoryReserveSize = 262144;
  37. /**
  38. * @var \Exception|null the exception that is being handled currently.
  39. */
  40. public $exception;
  41. /**
  42. * @var string Used to reserve memory for fatal error handler.
  43. */
  44. private $_memoryReserve;
  45. /**
  46. * @var \Exception from HHVM error that stores backtrace
  47. */
  48. private $_hhvmException;
  49. /**
  50. * Register this error handler.
  51. */
  52. public function register()
  53. {
  54. ini_set('display_errors', false);
  55. set_exception_handler([$this, 'handleException']);
  56. if (defined('HHVM_VERSION')) {
  57. set_error_handler([$this, 'handleHhvmError']);
  58. } else {
  59. set_error_handler([$this, 'handleError']);
  60. }
  61. if ($this->memoryReserveSize > 0) {
  62. $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
  63. }
  64. register_shutdown_function([$this, 'handleFatalError']);
  65. }
  66. /**
  67. * Unregisters this error handler by restoring the PHP error and exception handlers.
  68. */
  69. public function unregister()
  70. {
  71. restore_error_handler();
  72. restore_exception_handler();
  73. }
  74. /**
  75. * Handles uncaught PHP exceptions.
  76. *
  77. * This method is implemented as a PHP exception handler.
  78. *
  79. * @param \Exception $exception the exception that is not caught
  80. */
  81. public function handleException($exception)
  82. {
  83. if ($exception instanceof ExitException) {
  84. return;
  85. }
  86. $this->exception = $exception;
  87. // disable error capturing to avoid recursive errors while handling exceptions
  88. $this->unregister();
  89. // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
  90. // HTTP exceptions will override this value in renderException()
  91. if (PHP_SAPI !== 'cli') {
  92. http_response_code(500);
  93. }
  94. try {
  95. $this->logException($exception);
  96. if ($this->discardExistingOutput) {
  97. $this->clearOutput();
  98. }
  99. $this->renderException($exception);
  100. if (!YII_ENV_TEST) {
  101. \Yii::getLogger()->flush(true);
  102. if (defined('HHVM_VERSION')) {
  103. flush();
  104. }
  105. exit(1);
  106. }
  107. } catch (\Exception $e) {
  108. // an other exception could be thrown while displaying the exception
  109. $this->handleFallbackExceptionMessage($e, $exception);
  110. } catch (\Throwable $e) {
  111. // additional check for \Throwable introduced in PHP 7
  112. $this->handleFallbackExceptionMessage($e, $exception);
  113. }
  114. $this->exception = null;
  115. }
  116. /**
  117. * Handles exception thrown during exception processing in [[handleException()]].
  118. * @param \Exception|\Throwable $exception Exception that was thrown during main exception processing.
  119. * @param \Exception $previousException Main exception processed in [[handleException()]].
  120. * @since 2.0.11
  121. */
  122. protected function handleFallbackExceptionMessage($exception, $previousException)
  123. {
  124. $msg = "An Error occurred while handling another error:\n";
  125. $msg .= (string) $exception;
  126. $msg .= "\nPrevious exception:\n";
  127. $msg .= (string) $previousException;
  128. if (YII_DEBUG) {
  129. if (PHP_SAPI === 'cli') {
  130. echo $msg . "\n";
  131. } else {
  132. echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
  133. }
  134. } else {
  135. echo 'An internal server error occurred.';
  136. }
  137. $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
  138. error_log($msg);
  139. if (defined('HHVM_VERSION')) {
  140. flush();
  141. }
  142. exit(1);
  143. }
  144. /**
  145. * Handles HHVM execution errors such as warnings and notices.
  146. *
  147. * This method is used as a HHVM error handler. It will store exception that will
  148. * be used in fatal error handler
  149. *
  150. * @param int $code the level of the error raised.
  151. * @param string $message the error message.
  152. * @param string $file the filename that the error was raised in.
  153. * @param int $line the line number the error was raised at.
  154. * @param mixed $context
  155. * @param mixed $backtrace trace of error
  156. * @return bool whether the normal error handler continues.
  157. *
  158. * @throws ErrorException
  159. * @since 2.0.6
  160. */
  161. public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
  162. {
  163. if ($this->handleError($code, $message, $file, $line)) {
  164. return true;
  165. }
  166. if (E_ERROR & $code) {
  167. $exception = new ErrorException($message, $code, $code, $file, $line);
  168. $ref = new \ReflectionProperty('\Exception', 'trace');
  169. $ref->setAccessible(true);
  170. $ref->setValue($exception, $backtrace);
  171. $this->_hhvmException = $exception;
  172. }
  173. return false;
  174. }
  175. /**
  176. * Handles PHP execution errors such as warnings and notices.
  177. *
  178. * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
  179. *
  180. * @param int $code the level of the error raised.
  181. * @param string $message the error message.
  182. * @param string $file the filename that the error was raised in.
  183. * @param int $line the line number the error was raised at.
  184. * @return bool whether the normal error handler continues.
  185. *
  186. * @throws ErrorException
  187. */
  188. public function handleError($code, $message, $file, $line)
  189. {
  190. if (error_reporting() & $code) {
  191. // load ErrorException manually here because autoloading them will not work
  192. // when error occurs while autoloading a class
  193. if (!class_exists('yii\\base\\ErrorException', false)) {
  194. require_once __DIR__ . '/ErrorException.php';
  195. }
  196. $exception = new ErrorException($message, $code, $code, $file, $line);
  197. // in case error appeared in __toString method we can't throw any exception
  198. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  199. array_shift($trace);
  200. foreach ($trace as $frame) {
  201. if ($frame['function'] === '__toString') {
  202. $this->handleException($exception);
  203. if (defined('HHVM_VERSION')) {
  204. flush();
  205. }
  206. exit(1);
  207. }
  208. }
  209. throw $exception;
  210. }
  211. return false;
  212. }
  213. /**
  214. * Handles fatal PHP errors.
  215. */
  216. public function handleFatalError()
  217. {
  218. unset($this->_memoryReserve);
  219. // load ErrorException manually here because autoloading them will not work
  220. // when error occurs while autoloading a class
  221. if (!class_exists('yii\\base\\ErrorException', false)) {
  222. require_once __DIR__ . '/ErrorException.php';
  223. }
  224. $error = error_get_last();
  225. if (ErrorException::isFatalError($error)) {
  226. if (!empty($this->_hhvmException)) {
  227. $exception = $this->_hhvmException;
  228. } else {
  229. $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
  230. }
  231. $this->exception = $exception;
  232. $this->logException($exception);
  233. if ($this->discardExistingOutput) {
  234. $this->clearOutput();
  235. }
  236. $this->renderException($exception);
  237. // need to explicitly flush logs because exit() next will terminate the app immediately
  238. Yii::getLogger()->flush(true);
  239. if (defined('HHVM_VERSION')) {
  240. flush();
  241. }
  242. exit(1);
  243. }
  244. }
  245. /**
  246. * Renders the exception.
  247. * @param \Exception $exception the exception to be rendered.
  248. */
  249. abstract protected function renderException($exception);
  250. /**
  251. * Logs the given exception.
  252. * @param \Exception $exception the exception to be logged
  253. * @since 2.0.3 this method is now public.
  254. */
  255. public function logException($exception)
  256. {
  257. $category = get_class($exception);
  258. if ($exception instanceof HttpException) {
  259. $category = 'yii\\web\\HttpException:' . $exception->statusCode;
  260. } elseif ($exception instanceof \ErrorException) {
  261. $category .= ':' . $exception->getSeverity();
  262. }
  263. Yii::error($exception, $category);
  264. }
  265. /**
  266. * Removes all output echoed before calling this method.
  267. */
  268. public function clearOutput()
  269. {
  270. // the following manual level counting is to deal with zlib.output_compression set to On
  271. for ($level = ob_get_level(); $level > 0; --$level) {
  272. if (!@ob_end_clean()) {
  273. ob_clean();
  274. }
  275. }
  276. }
  277. /**
  278. * Converts an exception into a PHP error.
  279. *
  280. * This method can be used to convert exceptions inside of methods like `__toString()`
  281. * to PHP errors because exceptions cannot be thrown inside of them.
  282. * @param \Exception $exception the exception to convert to a PHP error.
  283. */
  284. public static function convertExceptionToError($exception)
  285. {
  286. trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
  287. }
  288. /**
  289. * Converts an exception into a simple string.
  290. * @param \Exception|\Error $exception the exception being converted
  291. * @return string the string representation of the exception.
  292. */
  293. public static function convertExceptionToString($exception)
  294. {
  295. if ($exception instanceof UserException) {
  296. return "{$exception->getName()}: {$exception->getMessage()}";
  297. }
  298. if (YII_DEBUG) {
  299. return static::convertExceptionToVerboseString($exception);
  300. }
  301. return 'An internal server error occurred.';
  302. }
  303. /**
  304. * Converts an exception into a string that has verbose information about the exception and its trace.
  305. * @param \Exception|\Error $exception the exception being converted
  306. * @return string the string representation of the exception.
  307. *
  308. * @since 2.0.14
  309. */
  310. public static function convertExceptionToVerboseString($exception)
  311. {
  312. if ($exception instanceof Exception) {
  313. $message = "Exception ({$exception->getName()})";
  314. } elseif ($exception instanceof ErrorException) {
  315. $message = (string)$exception->getName();
  316. } else {
  317. $message = 'Exception';
  318. }
  319. $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
  320. . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
  321. . "Stack trace:\n" . $exception->getTraceAsString();
  322. return $message;
  323. }
  324. }