ErrorHandler.php 13 KB

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