You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

328 lines
11KB

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