ErrorHandler.php 21 KB

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