ErrorHandler.php 21 KB

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