ErrorHandler.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. * @var bool whether this instance has been registered using `register()`
  51. */
  52. private $_registered = false;
  53. /**
  54. * Register this error handler.
  55. * @since 2.0.32 this will not do anything if the error handler was already registered
  56. */
  57. public function register()
  58. {
  59. if (!$this->_registered) {
  60. ini_set('display_errors', false);
  61. set_exception_handler([$this, 'handleException']);
  62. if (defined('HHVM_VERSION')) {
  63. set_error_handler([$this, 'handleHhvmError']);
  64. } else {
  65. set_error_handler([$this, 'handleError']);
  66. }
  67. if ($this->memoryReserveSize > 0) {
  68. $this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
  69. }
  70. register_shutdown_function([$this, 'handleFatalError']);
  71. $this->_registered = true;
  72. }
  73. }
  74. /**
  75. * Unregisters this error handler by restoring the PHP error and exception handlers.
  76. * @since 2.0.32 this will not do anything if the error handler was not registered
  77. */
  78. public function unregister()
  79. {
  80. if ($this->_registered) {
  81. restore_error_handler();
  82. restore_exception_handler();
  83. $this->_registered = false;
  84. }
  85. }
  86. /**
  87. * Handles uncaught PHP exceptions.
  88. *
  89. * This method is implemented as a PHP exception handler.
  90. *
  91. * @param \Exception $exception the exception that is not caught
  92. */
  93. public function handleException($exception)
  94. {
  95. if ($exception instanceof ExitException) {
  96. return;
  97. }
  98. $this->exception = $exception;
  99. // disable error capturing to avoid recursive errors while handling exceptions
  100. $this->unregister();
  101. // set preventive HTTP status code to 500 in case error handling somehow fails and headers are sent
  102. // HTTP exceptions will override this value in renderException()
  103. if (PHP_SAPI !== 'cli') {
  104. http_response_code(500);
  105. }
  106. try {
  107. $this->logException($exception);
  108. if ($this->discardExistingOutput) {
  109. $this->clearOutput();
  110. }
  111. $this->renderException($exception);
  112. if (!YII_ENV_TEST) {
  113. \Yii::getLogger()->flush(true);
  114. if (defined('HHVM_VERSION')) {
  115. flush();
  116. }
  117. exit(1);
  118. }
  119. } catch (\Exception $e) {
  120. // an other exception could be thrown while displaying the exception
  121. $this->handleFallbackExceptionMessage($e, $exception);
  122. } catch (\Throwable $e) {
  123. // additional check for \Throwable introduced in PHP 7
  124. $this->handleFallbackExceptionMessage($e, $exception);
  125. }
  126. $this->exception = null;
  127. }
  128. /**
  129. * Handles exception thrown during exception processing in [[handleException()]].
  130. * @param \Exception|\Throwable $exception Exception that was thrown during main exception processing.
  131. * @param \Exception $previousException Main exception processed in [[handleException()]].
  132. * @since 2.0.11
  133. */
  134. protected function handleFallbackExceptionMessage($exception, $previousException)
  135. {
  136. $msg = "An Error occurred while handling another error:\n";
  137. $msg .= (string) $exception;
  138. $msg .= "\nPrevious exception:\n";
  139. $msg .= (string) $previousException;
  140. if (YII_DEBUG) {
  141. if (PHP_SAPI === 'cli') {
  142. echo $msg . "\n";
  143. } else {
  144. echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, Yii::$app->charset) . '</pre>';
  145. }
  146. } else {
  147. echo 'An internal server error occurred.';
  148. }
  149. $msg .= "\n\$_SERVER = " . VarDumper::export($_SERVER);
  150. error_log($msg);
  151. if (defined('HHVM_VERSION')) {
  152. flush();
  153. }
  154. exit(1);
  155. }
  156. /**
  157. * Handles HHVM execution errors such as warnings and notices.
  158. *
  159. * This method is used as a HHVM error handler. It will store exception that will
  160. * be used in fatal error handler
  161. *
  162. * @param int $code the level of the error raised.
  163. * @param string $message the error message.
  164. * @param string $file the filename that the error was raised in.
  165. * @param int $line the line number the error was raised at.
  166. * @param mixed $context
  167. * @param mixed $backtrace trace of error
  168. * @return bool whether the normal error handler continues.
  169. *
  170. * @throws ErrorException
  171. * @since 2.0.6
  172. */
  173. public function handleHhvmError($code, $message, $file, $line, $context, $backtrace)
  174. {
  175. if ($this->handleError($code, $message, $file, $line)) {
  176. return true;
  177. }
  178. if (E_ERROR & $code) {
  179. $exception = new ErrorException($message, $code, $code, $file, $line);
  180. $ref = new \ReflectionProperty('\Exception', 'trace');
  181. $ref->setAccessible(true);
  182. $ref->setValue($exception, $backtrace);
  183. $this->_hhvmException = $exception;
  184. }
  185. return false;
  186. }
  187. /**
  188. * Handles PHP execution errors such as warnings and notices.
  189. *
  190. * This method is used as a PHP error handler. It will simply raise an [[ErrorException]].
  191. *
  192. * @param int $code the level of the error raised.
  193. * @param string $message the error message.
  194. * @param string $file the filename that the error was raised in.
  195. * @param int $line the line number the error was raised at.
  196. * @return bool whether the normal error handler continues.
  197. *
  198. * @throws ErrorException
  199. */
  200. public function handleError($code, $message, $file, $line)
  201. {
  202. if (error_reporting() & $code) {
  203. // load ErrorException manually here because autoloading them will not work
  204. // when error occurs while autoloading a class
  205. if (!class_exists('yii\\base\\ErrorException', false)) {
  206. require_once __DIR__ . '/ErrorException.php';
  207. }
  208. $exception = new ErrorException($message, $code, $code, $file, $line);
  209. if (PHP_VERSION_ID < 70400) {
  210. // prior to PHP 7.4 we can't throw exceptions inside of __toString() - it will result a fatal error
  211. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
  212. array_shift($trace);
  213. foreach ($trace as $frame) {
  214. if ($frame['function'] === '__toString') {
  215. $this->handleException($exception);
  216. if (defined('HHVM_VERSION')) {
  217. flush();
  218. }
  219. exit(1);
  220. }
  221. }
  222. }
  223. throw $exception;
  224. }
  225. return false;
  226. }
  227. /**
  228. * Handles fatal PHP errors.
  229. */
  230. public function handleFatalError()
  231. {
  232. unset($this->_memoryReserve);
  233. // load ErrorException manually here because autoloading them will not work
  234. // when error occurs while autoloading a class
  235. if (!class_exists('yii\\base\\ErrorException', false)) {
  236. require_once __DIR__ . '/ErrorException.php';
  237. }
  238. $error = error_get_last();
  239. if (ErrorException::isFatalError($error)) {
  240. if (!empty($this->_hhvmException)) {
  241. $exception = $this->_hhvmException;
  242. } else {
  243. $exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
  244. }
  245. $this->exception = $exception;
  246. $this->logException($exception);
  247. if ($this->discardExistingOutput) {
  248. $this->clearOutput();
  249. }
  250. $this->renderException($exception);
  251. // need to explicitly flush logs because exit() next will terminate the app immediately
  252. Yii::getLogger()->flush(true);
  253. if (defined('HHVM_VERSION')) {
  254. flush();
  255. }
  256. exit(1);
  257. }
  258. }
  259. /**
  260. * Renders the exception.
  261. * @param \Exception $exception the exception to be rendered.
  262. */
  263. abstract protected function renderException($exception);
  264. /**
  265. * Logs the given exception.
  266. * @param \Exception $exception the exception to be logged
  267. * @since 2.0.3 this method is now public.
  268. */
  269. public function logException($exception)
  270. {
  271. $category = get_class($exception);
  272. if ($exception instanceof HttpException) {
  273. $category = 'yii\\web\\HttpException:' . $exception->statusCode;
  274. } elseif ($exception instanceof \ErrorException) {
  275. $category .= ':' . $exception->getSeverity();
  276. }
  277. Yii::error($exception, $category);
  278. }
  279. /**
  280. * Removes all output echoed before calling this method.
  281. */
  282. public function clearOutput()
  283. {
  284. // the following manual level counting is to deal with zlib.output_compression set to On
  285. for ($level = ob_get_level(); $level > 0; --$level) {
  286. if (!@ob_end_clean()) {
  287. ob_clean();
  288. }
  289. }
  290. }
  291. /**
  292. * Converts an exception into a PHP error.
  293. *
  294. * This method can be used to convert exceptions inside of methods like `__toString()`
  295. * to PHP errors because exceptions cannot be thrown inside of them.
  296. * @param \Exception $exception the exception to convert to a PHP error.
  297. */
  298. public static function convertExceptionToError($exception)
  299. {
  300. trigger_error(static::convertExceptionToString($exception), E_USER_ERROR);
  301. }
  302. /**
  303. * Converts an exception into a simple string.
  304. * @param \Exception|\Error $exception the exception being converted
  305. * @return string the string representation of the exception.
  306. */
  307. public static function convertExceptionToString($exception)
  308. {
  309. if ($exception instanceof UserException) {
  310. return "{$exception->getName()}: {$exception->getMessage()}";
  311. }
  312. if (YII_DEBUG) {
  313. return static::convertExceptionToVerboseString($exception);
  314. }
  315. return 'An internal server error occurred.';
  316. }
  317. /**
  318. * Converts an exception into a string that has verbose information about the exception and its trace.
  319. * @param \Exception|\Error $exception the exception being converted
  320. * @return string the string representation of the exception.
  321. *
  322. * @since 2.0.14
  323. */
  324. public static function convertExceptionToVerboseString($exception)
  325. {
  326. if ($exception instanceof Exception) {
  327. $message = "Exception ({$exception->getName()})";
  328. } elseif ($exception instanceof ErrorException) {
  329. $message = (string)$exception->getName();
  330. } else {
  331. $message = 'Exception';
  332. }
  333. $message .= " '" . get_class($exception) . "' with message '{$exception->getMessage()}' \n\nin "
  334. . $exception->getFile() . ':' . $exception->getLine() . "\n\n"
  335. . "Stack trace:\n" . $exception->getTraceAsString();
  336. return $message;
  337. }
  338. }