ErrorHandler.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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', 'Trying to access array offset on value of type null'];
  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. if ($exception instanceof HttpException) {
  188. $array['status'] = $exception->statusCode;
  189. }
  190. if (YII_DEBUG) {
  191. $array['type'] = get_class($exception);
  192. }
  193. return $array;
  194. }
  195. /**
  196. * Converts special characters to HTML entities.
  197. * @param string $text to encode.
  198. * @return string encoded original text.
  199. */
  200. public function htmlEncode($text)
  201. {
  202. return htmlspecialchars($text, ENT_NOQUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
  203. }
  204. /**
  205. * Adds informational links to the given PHP type/class.
  206. * @param string $code type/class name to be linkified.
  207. * @return string linkified with HTML type/class name.
  208. */
  209. public function addTypeLinks($code)
  210. {
  211. if (preg_match('/(.*?)::([^(]+)/', $code, $matches)) {
  212. $class = $matches[1];
  213. $method = $matches[2];
  214. $text = $this->htmlEncode($class) . '::' . $this->htmlEncode($method);
  215. } else {
  216. $class = $code;
  217. $method = null;
  218. $text = $this->htmlEncode($class);
  219. }
  220. $url = null;
  221. $shouldGenerateLink = true;
  222. if ($method !== null && substr_compare($method, '{closure}', -9) !== 0) {
  223. $reflection = new \ReflectionClass($class);
  224. if ($reflection->hasMethod($method)) {
  225. $reflectionMethod = $reflection->getMethod($method);
  226. $shouldGenerateLink = $reflectionMethod->isPublic() || $reflectionMethod->isProtected();
  227. } else {
  228. $shouldGenerateLink = false;
  229. }
  230. }
  231. if ($shouldGenerateLink) {
  232. $url = $this->getTypeUrl($class, $method);
  233. }
  234. if ($url === null) {
  235. return $text;
  236. }
  237. return '<a href="' . $url . '" target="_blank">' . $text . '</a>';
  238. }
  239. /**
  240. * Returns the informational link URL for a given PHP type/class.
  241. * @param string $class the type or class name.
  242. * @param string|null $method the method name.
  243. * @return string|null the informational link URL.
  244. * @see addTypeLinks()
  245. */
  246. protected function getTypeUrl($class, $method)
  247. {
  248. if (strncmp($class, 'yii\\', 4) !== 0) {
  249. return null;
  250. }
  251. $page = $this->htmlEncode(strtolower(str_replace('\\', '-', $class)));
  252. $url = "http://www.yiiframework.com/doc-2.0/$page.html";
  253. if ($method) {
  254. $url .= "#$method()-detail";
  255. }
  256. return $url;
  257. }
  258. /**
  259. * Renders a view file as a PHP script.
  260. * @param string $_file_ the view file.
  261. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
  262. * @return string the rendering result
  263. */
  264. public function renderFile($_file_, $_params_)
  265. {
  266. $_params_['handler'] = $this;
  267. if ($this->exception instanceof ErrorException || !Yii::$app->has('view')) {
  268. ob_start();
  269. ob_implicit_flush(false);
  270. extract($_params_, EXTR_OVERWRITE);
  271. require Yii::getAlias($_file_);
  272. return ob_get_clean();
  273. }
  274. $view = Yii::$app->getView();
  275. $view->clear();
  276. return $view->renderFile($_file_, $_params_, $this);
  277. }
  278. /**
  279. * Renders the previous exception stack for a given Exception.
  280. * @param \Exception $exception the exception whose precursors should be rendered.
  281. * @return string HTML content of the rendered previous exceptions.
  282. * Empty string if there are none.
  283. */
  284. public function renderPreviousExceptions($exception)
  285. {
  286. if (($previous = $exception->getPrevious()) !== null) {
  287. return $this->renderFile($this->previousExceptionView, ['exception' => $previous]);
  288. }
  289. return '';
  290. }
  291. /**
  292. * Renders a single call stack element.
  293. * @param string|null $file name where call has happened.
  294. * @param int|null $line number on which call has happened.
  295. * @param string|null $class called class name.
  296. * @param string|null $method called function/method name.
  297. * @param array $args array of method arguments.
  298. * @param int $index number of the call stack element.
  299. * @return string HTML content of the rendered call stack element.
  300. */
  301. public function renderCallStackItem($file, $line, $class, $method, $args, $index)
  302. {
  303. $lines = [];
  304. $begin = $end = 0;
  305. if ($file !== null && $line !== null) {
  306. $line--; // adjust line number from one-based to zero-based
  307. $lines = @file($file);
  308. if ($line < 0 || $lines === false || ($lineCount = count($lines)) < $line) {
  309. return '';
  310. }
  311. $half = (int) (($index === 1 ? $this->maxSourceLines : $this->maxTraceSourceLines) / 2);
  312. $begin = $line - $half > 0 ? $line - $half : 0;
  313. $end = $line + $half < $lineCount ? $line + $half : $lineCount - 1;
  314. }
  315. return $this->renderFile($this->callStackItemView, [
  316. 'file' => $file,
  317. 'line' => $line,
  318. 'class' => $class,
  319. 'method' => $method,
  320. 'index' => $index,
  321. 'lines' => $lines,
  322. 'begin' => $begin,
  323. 'end' => $end,
  324. 'args' => $args,
  325. ]);
  326. }
  327. /**
  328. * Renders call stack.
  329. * @param \Exception|\ParseError $exception exception to get call stack from
  330. * @return string HTML content of the rendered call stack.
  331. * @since 2.0.12
  332. */
  333. public function renderCallStack($exception)
  334. {
  335. $out = '<ul>';
  336. $out .= $this->renderCallStackItem($exception->getFile(), $exception->getLine(), null, null, [], 1);
  337. for ($i = 0, $trace = $exception->getTrace(), $length = count($trace); $i < $length; ++$i) {
  338. $file = !empty($trace[$i]['file']) ? $trace[$i]['file'] : null;
  339. $line = !empty($trace[$i]['line']) ? $trace[$i]['line'] : null;
  340. $class = !empty($trace[$i]['class']) ? $trace[$i]['class'] : null;
  341. $function = null;
  342. if (!empty($trace[$i]['function']) && $trace[$i]['function'] !== 'unknown') {
  343. $function = $trace[$i]['function'];
  344. }
  345. $args = !empty($trace[$i]['args']) ? $trace[$i]['args'] : [];
  346. $out .= $this->renderCallStackItem($file, $line, $class, $function, $args, $i + 2);
  347. }
  348. $out .= '</ul>';
  349. return $out;
  350. }
  351. /**
  352. * Renders the global variables of the request.
  353. * List of global variables is defined in [[displayVars]].
  354. * @return string the rendering result
  355. * @see displayVars
  356. */
  357. public function renderRequest()
  358. {
  359. $request = '';
  360. foreach ($this->displayVars as $name) {
  361. if (!empty($GLOBALS[$name])) {
  362. $request .= '$' . $name . ' = ' . VarDumper::export($GLOBALS[$name]) . ";\n\n";
  363. }
  364. }
  365. return '<pre>' . $this->htmlEncode(rtrim($request, "\n")) . '</pre>';
  366. }
  367. /**
  368. * Determines whether given name of the file belongs to the framework.
  369. * @param string $file name to be checked.
  370. * @return bool whether given name of the file belongs to the framework.
  371. */
  372. public function isCoreFile($file)
  373. {
  374. return $file === null || strpos(realpath($file), YII2_PATH . DIRECTORY_SEPARATOR) === 0;
  375. }
  376. /**
  377. * Creates HTML containing link to the page with the information on given HTTP status code.
  378. * @param int $statusCode to be used to generate information link.
  379. * @param string $statusDescription Description to display after the the status code.
  380. * @return string generated HTML with HTTP status code information.
  381. */
  382. public function createHttpStatusLink($statusCode, $statusDescription)
  383. {
  384. return '<a href="http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#' . (int) $statusCode . '" target="_blank">HTTP ' . (int) $statusCode . ' &ndash; ' . $statusDescription . '</a>';
  385. }
  386. /**
  387. * Creates string containing HTML link which refers to the home page of determined web-server software
  388. * and its full name.
  389. * @return string server software information hyperlink.
  390. */
  391. public function createServerInformationLink()
  392. {
  393. $serverUrls = [
  394. 'http://httpd.apache.org/' => ['apache'],
  395. 'http://nginx.org/' => ['nginx'],
  396. 'http://lighttpd.net/' => ['lighttpd'],
  397. 'http://gwan.com/' => ['g-wan', 'gwan'],
  398. 'http://iis.net/' => ['iis', 'services'],
  399. 'https://secure.php.net/manual/en/features.commandline.webserver.php' => ['development'],
  400. ];
  401. if (isset($_SERVER['SERVER_SOFTWARE'])) {
  402. foreach ($serverUrls as $url => $keywords) {
  403. foreach ($keywords as $keyword) {
  404. if (stripos($_SERVER['SERVER_SOFTWARE'], $keyword) !== false) {
  405. return '<a href="' . $url . '" target="_blank">' . $this->htmlEncode($_SERVER['SERVER_SOFTWARE']) . '</a>';
  406. }
  407. }
  408. }
  409. }
  410. return '';
  411. }
  412. /**
  413. * Creates string containing HTML link which refers to the page with the current version
  414. * of the framework and version number text.
  415. * @return string framework version information hyperlink.
  416. */
  417. public function createFrameworkVersionLink()
  418. {
  419. return '<a href="http://github.com/yiisoft/yii2/" target="_blank">' . $this->htmlEncode(Yii::getVersion()) . '</a>';
  420. }
  421. /**
  422. * Converts arguments array to its string representation.
  423. *
  424. * @param array $args arguments array to be converted
  425. * @return string string representation of the arguments array
  426. */
  427. public function argumentsToString($args)
  428. {
  429. $count = 0;
  430. $isAssoc = $args !== array_values($args);
  431. foreach ($args as $key => $value) {
  432. $count++;
  433. if ($count >= 5) {
  434. if ($count > 5) {
  435. unset($args[$key]);
  436. } else {
  437. $args[$key] = '...';
  438. }
  439. continue;
  440. }
  441. if (is_object($value)) {
  442. $args[$key] = '<span class="title">' . $this->htmlEncode(get_class($value)) . '</span>';
  443. } elseif (is_bool($value)) {
  444. $args[$key] = '<span class="keyword">' . ($value ? 'true' : 'false') . '</span>';
  445. } elseif (is_string($value)) {
  446. $fullValue = $this->htmlEncode($value);
  447. if (mb_strlen($value, 'UTF-8') > 32) {
  448. $displayValue = $this->htmlEncode(mb_substr($value, 0, 32, 'UTF-8')) . '...';
  449. $args[$key] = "<span class=\"string\" title=\"$fullValue\">'$displayValue'</span>";
  450. } else {
  451. $args[$key] = "<span class=\"string\">'$fullValue'</span>";
  452. }
  453. } elseif (is_array($value)) {
  454. $args[$key] = '[' . $this->argumentsToString($value) . ']';
  455. } elseif ($value === null) {
  456. $args[$key] = '<span class="keyword">null</span>';
  457. } elseif (is_resource($value)) {
  458. $args[$key] = '<span class="keyword">resource</span>';
  459. } else {
  460. $args[$key] = '<span class="number">' . $value . '</span>';
  461. }
  462. if (is_string($key)) {
  463. $args[$key] = '<span class="string">\'' . $this->htmlEncode($key) . "'</span> => $args[$key]";
  464. } elseif ($isAssoc) {
  465. $args[$key] = "<span class=\"number\">$key</span> => $args[$key]";
  466. }
  467. }
  468. return implode(', ', $args);
  469. }
  470. /**
  471. * Returns human-readable exception name.
  472. * @param \Exception $exception
  473. * @return string|null human-readable exception name or null if it cannot be determined
  474. */
  475. public function getExceptionName($exception)
  476. {
  477. if ($exception instanceof \yii\base\Exception || $exception instanceof \yii\base\InvalidCallException || $exception instanceof \yii\base\InvalidParamException || $exception instanceof \yii\base\UnknownMethodException) {
  478. return $exception->getName();
  479. }
  480. return null;
  481. }
  482. /**
  483. * @return bool if simple HTML should be rendered
  484. * @since 2.0.12
  485. */
  486. protected function shouldRenderSimpleHtml()
  487. {
  488. return YII_ENV_TEST || Yii::$app->request->getIsAjax();
  489. }
  490. }