ErrorHandler.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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\web;
  8. use common\helpers\DingTalk;
  9. use common\helpers\LoggerTool;
  10. use common\helpers\Tool;
  11. use Yii;
  12. use yii\base\ErrorException;
  13. use yii\base\Exception;
  14. use yii\base\UserException;
  15. use yii\helpers\VarDumper;
  16. /**
  17. * ErrorHandler handles uncaught PHP errors and exceptions.
  18. *
  19. * ErrorHandler displays these errors using appropriate views based on the
  20. * nature of the errors and the mode the application runs at.
  21. *
  22. * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
  23. * You can access that instance via `Yii::$app->errorHandler`.
  24. *
  25. * For more details and usage information on ErrorHandler, see the [guide article on handling errors](guide:runtime-handling-errors).
  26. *
  27. * @author Qiang Xue <qiang.xue@gmail.com>
  28. * @author Timur Ruziev <resurtm@gmail.com>
  29. * @since 2.0
  30. */
  31. class ErrorHandler extends \yii\base\ErrorHandler
  32. {
  33. /**
  34. * @var int maximum number of source code lines to be displayed. Defaults to 19.
  35. */
  36. public $maxSourceLines = 19;
  37. /**
  38. * @var int maximum number of trace source code lines to be displayed. Defaults to 13.
  39. */
  40. public $maxTraceSourceLines = 13;
  41. /**
  42. * @var string the route (e.g. `site/error`) to the controller action that will be used
  43. * to display external errors. Inside the action, it can retrieve the error information
  44. * using `Yii::$app->errorHandler->exception`. This property defaults to null, meaning ErrorHandler
  45. * will handle the error display.
  46. */
  47. public $errorAction;
  48. /**
  49. * @var string the path of the view file for rendering exceptions without call stack information.
  50. */
  51. public $errorView = '@yii/views/errorHandler/error.php';
  52. /**
  53. * @var string the path of the view file for rendering exceptions.
  54. */
  55. public $exceptionView = '@yii/views/errorHandler/exception.php';
  56. /**
  57. * @var string the path of the view file for rendering exceptions and errors call stack element.
  58. */
  59. public $callStackItemView = '@yii/views/errorHandler/callStackItem.php';
  60. /**
  61. * @var string the path of the view file for rendering previous exceptions.
  62. */
  63. public $previousExceptionView = '@yii/views/errorHandler/previousException.php';
  64. /**
  65. * @var array list of the PHP predefined variables that should be displayed on the error page.
  66. * Note that a variable must be accessible via `$GLOBALS`. Otherwise it won't be displayed.
  67. * Defaults to `['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION']`.
  68. * @see renderRequest()
  69. * @since 2.0.7
  70. */
  71. public $displayVars = ['_GET', '_POST', '_FILES', '_COOKIE', '_SESSION'];
  72. /**
  73. * @var string trace line with placeholders to be be substituted.
  74. * The placeholders are {file}, {line} and {text} and the string should be as follows.
  75. *
  76. * `File: {file} - Line: {line} - Text: {text}`
  77. *
  78. * @example <a href="ide://open?file={file}&line={line}">{html}</a>
  79. * @see https://github.com/yiisoft/yii2-debug#open-files-in-ide
  80. * @since 2.0.14
  81. */
  82. public $traceLine = '{html}';
  83. /**
  84. * Renders the exception.
  85. * @param \Exception|\Error $exception the exception to be rendered.
  86. */
  87. protected function renderException($exception)
  88. {
  89. if (Yii::$app->has('response')) {
  90. $response = Yii::$app->getResponse();
  91. // reset parameters of response to avoid interference with partially created response data
  92. // in case the error occurred while sending the response.
  93. $response->isSent = false;
  94. $response->stream = null;
  95. $response->data = null;
  96. $response->content = null;
  97. } else {
  98. $response = new Response();
  99. }
  100. $response->setStatusCodeByException($exception);
  101. $useErrorView = $response->format === Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
  102. if ($useErrorView && $this->errorAction !== null) {
  103. Yii::$app->view->clear();
  104. $result = Yii::$app->runAction($this->errorAction);
  105. if ($result instanceof Response) {
  106. $response = $result;
  107. } else {
  108. $response->data = $result;
  109. }
  110. } elseif ($response->format === Response::FORMAT_HTML) {
  111. if ($this->shouldRenderSimpleHtml()) {
  112. // AJAX request
  113. $response->data = '<pre>' . $this->htmlEncode(static::convertExceptionToString($exception)) . '</pre>';
  114. } else {
  115. // if there is an error during error rendering it's useful to
  116. // display PHP error in debug mode instead of a blank screen
  117. if (YII_DEBUG) {
  118. ini_set('display_errors', 1);
  119. }
  120. $file = $useErrorView ? $this->errorView : $this->exceptionView;
  121. $response->data = $this->renderFile($file, [
  122. 'exception' => $exception,
  123. ]);
  124. }
  125. } elseif ($response->format === Response::FORMAT_RAW) {
  126. $response->data = static::convertExceptionToString($exception);
  127. } else {
  128. $response->data = $this->convertExceptionToArray($exception);
  129. }
  130. $response->send();
  131. }
  132. /**
  133. * Converts an exception into an array.
  134. * @param \Exception|\Error $exception the exception being converted
  135. * @return array the array representation of the exception.
  136. */
  137. protected function convertExceptionToArray($exception)
  138. {
  139. if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) {
  140. $exception = new HttpException(500, Yii::t('yii', 'An internal server error occurred.'));
  141. }
  142. $errorOutline = ['AR_', 'PHP', 'Undefined', 'Undefined index', 'SQLSTATE'];
  143. foreach ($errorOutline as $item) {
  144. if (false !== strpos($exception->getMessage(), $item)) {
  145. $it = [
  146. 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',
  147. 'message' => '(NG)提醒:' . $exception->getMessage(),
  148. 'code' => $exception->getCode(),
  149. ];
  150. if ($exception instanceof HttpException) {
  151. $it['status'] = $exception->statusCode;
  152. }
  153. if (YII_DEBUG) {
  154. $it['type'] = get_class($exception);
  155. if (!$exception instanceof UserException) {
  156. $it['file'] = $exception->getFile();
  157. $it['line'] = $exception->getLine();
  158. $it['stack-trace'] = explode("\n", $exception->getTraceAsString());
  159. if ($exception instanceof \yii\db\Exception) {
  160. $it['error-info'] = $exception->errorInfo;
  161. }
  162. }
  163. }
  164. if (($prev = $exception->getPrevious()) !== null) {
  165. $it['previous'] = $this->convertExceptionToArray($prev);
  166. }
  167. // 错误日志写入
  168. $it['trace-id'] = Tool::generateId();
  169. LoggerTool::error($it);
  170. // 提醒只报出基本错误
  171. unset($it['stack-trace']);
  172. // 发送钉钉提醒
  173. DingTalk::sendNotice($it);
  174. $array = [
  175. 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',
  176. 'message' => 'Bad request! Please contact the customer service personnel.',
  177. 'code' => $exception->getCode(),
  178. ];
  179. return $array;
  180. }
  181. }
  182. $array = [
  183. 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',
  184. 'message' => $exception->getMessage(),
  185. 'code' => $exception->getCode(),
  186. ];
  187. return $array;
  188. }
  189. /**
  190. * Converts special characters to HTML entities.
  191. * @param string $text to encode.
  192. * @return string encoded original text.
  193. */
  194. public function htmlEncode($text)
  195. {
  196. return htmlspecialchars($text, ENT_NOQUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
  197. }
  198. /**
  199. * Adds informational links to the given PHP type/class.
  200. * @param string $code type/class name to be linkified.
  201. * @return string linkified with HTML type/class name.
  202. */
  203. public function addTypeLinks($code)
  204. {
  205. if (preg_match('/(.*?)::([^(]+)/', $code, $matches)) {
  206. $class = $matches[1];
  207. $method = $matches[2];
  208. $text = $this->htmlEncode($class) . '::' . $this->htmlEncode($method);
  209. } else {
  210. $class = $code;
  211. $method = null;
  212. $text = $this->htmlEncode($class);
  213. }
  214. $url = null;
  215. $shouldGenerateLink = true;
  216. if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) {
  217. $reflection = new \ReflectionClass($class);
  218. if ($reflection->hasMethod($method)) {
  219. $reflectionMethod = $reflection->getMethod($method);
  220. $shouldGenerateLink = $reflectionMethod->isPublic() || $reflectionMethod->isProtected();
  221. } else {
  222. $shouldGenerateLink = false;
  223. }
  224. }
  225. if ($shouldGenerateLink) {
  226. $url = $this->getTypeUrl($class, $method);
  227. }
  228. if ($url === null) {
  229. return $text;
  230. }
  231. return '<a href="' . $url . '" target="_blank">' . $text . '</a>';
  232. }
  233. /**
  234. * Returns the informational link URL for a given PHP type/class.
  235. * @param string $class the type or class name.
  236. * @param string|null $method the method name.
  237. * @return string|null the informational link URL.
  238. * @see addTypeLinks()
  239. */
  240. protected function getTypeUrl($class, $method)
  241. {
  242. if (strncmp($class, 'yii\\', 4) !== 0) {
  243. return null;
  244. }
  245. $page = $this->htmlEncode(strtolower(str_replace('\\', '-', $class)));
  246. $url = "http://www.yiiframework.com/doc-2.0/$page.html";
  247. if ($method) {
  248. $url .= "#$method()-detail";
  249. }
  250. return $url;
  251. }
  252. /**
  253. * Renders a view file as a PHP script.
  254. * @param string $_file_ the view file.
  255. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
  256. * @return string the rendering result
  257. */
  258. public function renderFile($_file_, $_params_)
  259. {
  260. $_params_['handler'] = $this;
  261. if ($this->exception instanceof ErrorException || !Yii::$app->has('view')) {
  262. ob_start();
  263. ob_implicit_flush(false);
  264. extract($_params_, EXTR_OVERWRITE);
  265. require Yii::getAlias($_file_);
  266. return ob_get_clean();
  267. }
  268. $view = Yii::$app->getView();
  269. $view->clear();
  270. return $view->renderFile($_file_, $_params_, $this);
  271. }
  272. /**
  273. * Renders the previous exception stack for a given Exception.
  274. * @param \Exception $exception the exception whose precursors should be rendered.
  275. * @return string HTML content of the rendered previous exceptions.
  276. * Empty string if there are none.
  277. */
  278. public function renderPreviousExceptions($exception)
  279. {
  280. if (($previous = $exception->getPrevious()) !== null) {
  281. return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
  282. }
  283. return '';
  284. }
  285. /**
  286. * Renders a single call stack element.
  287. * @param string|null $file name where call has happened.
  288. * @param int|null $line number on which call has happened.
  289. * @param string|null $class called class name.
  290. * @param string|null $method called function/method name.
  291. * @param array $args array of method arguments.
  292. * @param int $index number of the call stack element.
  293. * @return string HTML content of the rendered call stack element.
  294. */
  295. public function renderCallStackItem($file, $line, $class, $method, $args, $index)
  296. {
  297. $lines = [];
  298. $begin = $end = 0;
  299. if ($file !== null && $line !== null) {
  300. $line--; // adjust line number from one-based to zero-based
  301. $lines = @file($file);
  302. if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line) {
  303. return '';
  304. }
  305. $half = (int) (($index === 1 ? $this->maxSourceLines : $this->maxTraceSourceLines) / 2);
  306. $begin = $line - $half > 0 ? $line - $half : 0;
  307. $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
  308. }
  309. return $this->renderFile($this->callStackItemView, [
  310. 'file' => $file,
  311. 'line' => $line,
  312. 'class' => $class,
  313. 'method' => $method,
  314. 'index' => $index,
  315. 'lines' => $lines,
  316. 'begin' => $begin,
  317. 'end' => $end,
  318. 'args' => $args,
  319. ]);
  320. }
  321. /**
  322. * Renders call stack.
  323. * @param \Exception|\ParseError $exception exception to get call stack from
  324. * @return string HTML content of the rendered call stack.
  325. * @since 2.0.12
  326. */
  327. public function renderCallStack($exception)
  328. {
  329. $out = '<ul>';
  330. $out .= $this->renderCallStackItem($exception->getFile(), $exception->getLine(), null, null, [], 1);
  331. for ($i = 0, $trace = $exception->getTrace(), $length = count($trace); $i < $length; ++$i) {
  332. $file = !empty($trace[$i]['file']) ? $trace[$i]['file'] : null;
  333. $line = !empty($trace[$i]['line']) ? $trace[$i]['line'] : null;
  334. $class = !empty($trace[$i]['class']) ? $trace[$i]['class'] : null;
  335. $function = null;
  336. if (!empty($trace[$i]['function']) && $trace[$i]['function'] !== 'unknown') {
  337. $function = $trace[$i]['function'];
  338. }
  339. $args = !empty($trace[$i]['args']) ? $trace[$i]['args'] : [];
  340. $out .= $this->renderCallStackItem($file, $line, $class, $function, $args, $i + 2);
  341. }
  342. $out .= '</ul>';
  343. return $out;
  344. }
  345. /**
  346. * Renders the global variables of the request.
  347. * List of global variables is defined in [[displayVars]].
  348. * @return string the rendering result
  349. * @see displayVars
  350. */
  351. public function renderRequest()
  352. {
  353. $request = '';
  354. foreach ($this->displayVars as $name) {
  355. if (!empty($GLOBALS[$name])) {
  356. $request .= '$' . $name . ' = ' . VarDumper::export($GLOBALS[$name]) . ";\n\n";
  357. }
  358. }
  359. return '<pre>' . $this->htmlEncode(rtrim($request, "\n")) . '</pre>';
  360. }
  361. /**
  362. * Determines whether given name of the file belongs to the framework.
  363. * @param string $file name to be checked.
  364. * @return bool whether given name of the file belongs to the framework.
  365. */
  366. public function isCoreFile($file)
  367. {
  368. return $file === null || strpos(realpath($file), YII2_PATH . DIRECTORY_SEPARATOR) === 0;
  369. }
  370. /**
  371. * Creates HTML containing link to the page with the information on given HTTP status code.
  372. * @param int $statusCode to be used to generate information link.
  373. * @param string $statusDescription Description to display after the the status code.
  374. * @return string generated HTML with HTTP status code information.
  375. */
  376. public function createHttpStatusLink($statusCode, $statusDescription)
  377. {
  378. return '<a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#' . (int) $statusCode . '" target="_blank">HTTP ' . (int) $statusCode . ' &ndash; ' . $statusDescription . '</a>';
  379. }
  380. /**
  381. * Creates string containing HTML link which refers to the home page of determined web-server software
  382. * and its full name.
  383. * @return string server software information hyperlink.
  384. */
  385. public function createServerInformationLink()
  386. {
  387. $serverUrls = [
  388. 'http://httpd.apache.org/' => ['apache'],
  389. 'http://nginx.org/' => ['nginx'],
  390. 'http://lighttpd.net/' => ['lighttpd'],
  391. 'http://gwan.com/' => ['g-wan', 'gwan'],
  392. 'http://iis.net/' => ['iis', 'services'],
  393. 'https://secure.php.net/manual/en/features.commandline.webserver.php' => ['development'],
  394. ];
  395. if (isset($_SERVER['SERVER_SOFTWARE'])) {
  396. foreach ($serverUrls as $url => $keywords) {
  397. foreach ($keywords as $keyword) {
  398. if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
  399. return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
  400. }
  401. }
  402. }
  403. }
  404. return '';
  405. }
  406. /**
  407. * Creates string containing HTML link which refers to the page with the current version
  408. * of the framework and version number text.
  409. * @return string framework version information hyperlink.
  410. */
  411. public function createFrameworkVersionLink()
  412. {
  413. return '<a href="http://github.com/yiisoft/yii2/" target="_blank">' . $this->htmlEncode(Yii::getVersion()) . '</a>';
  414. }
  415. /**
  416. * Converts arguments array to its string representation.
  417. *
  418. * @param array $args arguments array to be converted
  419. * @return string string representation of the arguments array
  420. */
  421. public function argumentsToString($args)
  422. {
  423. $count = 0;
  424. $isAssoc = $args !== array_values($args);
  425. foreach ($args as $key => $value) {
  426. $count++;
  427. if ($count >= 5) {
  428. if ($count > 5) {
  429. unset($args[$key]);
  430. } else {
  431. $args[$key] = '...';
  432. }
  433. continue;
  434. }
  435. if (is_object($value)) {
  436. $args[$key] = '<span class="title">' . $this->htmlEncode(get_class($value)) . '</span>';
  437. } elseif (is_bool($value)) {
  438. $args[$key] = '<span class="keyword">' . ($value ? 'true' : 'false') . '</span>';
  439. } elseif (is_string($value)) {
  440. $fullValue = $this->htmlEncode($value);
  441. if (mb_strlen($value, 'UTF-8') > 32) {
  442. $displayValue = $this->htmlEncode(mb_substr($value, 0, 32, 'UTF-8')) . '...';
  443. $args[$key] = "<span class=\"string\" title=\"$fullValue\">'$displayValue'</span>";
  444. } else {
  445. $args[$key] = "<span class=\"string\">'$fullValue'</span>";
  446. }
  447. } elseif (is_array($value)) {
  448. $args[$key] = '[' . $this->argumentsToString($value) . ']';
  449. } elseif ($value === null) {
  450. $args[$key] = '<span class="keyword">null</span>';
  451. } elseif (is_resource($value)) {
  452. $args[$key] = '<span class="keyword">resource</span>';
  453. } else {
  454. $args[$key] = '<span class="number">' . $value . '</span>';
  455. }
  456. if (is_string($key)) {
  457. $args[$key] = '<span class="string">\'' . $this->htmlEncode($key) . "'</span> => $args[$key]";
  458. } elseif ($isAssoc) {
  459. $args[$key] = "<span class=\"number\">$key</span> => $args[$key]";
  460. }
  461. }
  462. return implode(', ', $args);
  463. }
  464. /**
  465. * Returns human-readable exception name.
  466. * @param \Exception $exception
  467. * @return string|null human-readable exception name or null if it cannot be determined
  468. */
  469. public function getExceptionName($exception)
  470. {
  471. if ($exception instanceof \yii\base\Exception || $exception instanceof \yii\base\InvalidCallException || $exception instanceof \yii\base\InvalidParamException || $exception instanceof \yii\base\UnknownMethodException) {
  472. return $exception->getName();
  473. }
  474. return null;
  475. }
  476. /**
  477. * @return bool if simple HTML should be rendered
  478. * @since 2.0.12
  479. */
  480. protected function shouldRenderSimpleHtml()
  481. {
  482. return YII_ENV_TEST || Yii::$app->request->getIsAjax();
  483. }
  484. }