Handle.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\exception;
  12. use Exception;
  13. use think\console\Output;
  14. use think\Container;
  15. use think\Response;
  16. class Handle
  17. {
  18. protected $render;
  19. protected $ignoreReport = [
  20. '\\think\\exception\\HttpException',
  21. ];
  22. public function setRender($render)
  23. {
  24. $this->render = $render;
  25. }
  26. /**
  27. * Report or log an exception.
  28. *
  29. * @access public
  30. * @param \Exception $exception
  31. * @return void
  32. */
  33. public function report(Exception $exception)
  34. {
  35. if (!$this->isIgnoreReport($exception)) {
  36. // 收集异常数据
  37. if (Container::get('app')->isDebug()) {
  38. $data = [
  39. 'file' => $exception->getFile(),
  40. 'line' => $exception->getLine(),
  41. 'message' => $this->getMessage($exception),
  42. 'code' => $this->getCode($exception),
  43. ];
  44. $log = "[{$data['code']}]{$data['message']}[{$data['file']}:{$data['line']}]";
  45. } else {
  46. $data = [
  47. 'code' => $this->getCode($exception),
  48. 'message' => $this->getMessage($exception),
  49. ];
  50. $log = "[{$data['code']}]{$data['message']}";
  51. }
  52. if (Container::get('app')->config('log.record_trace')) {
  53. $log .= "\r\n" . $exception->getTraceAsString();
  54. }
  55. Container::get('log')->record($log, 'error');
  56. }
  57. }
  58. protected function isIgnoreReport(Exception $exception)
  59. {
  60. foreach ($this->ignoreReport as $class) {
  61. if ($exception instanceof $class) {
  62. return true;
  63. }
  64. }
  65. return false;
  66. }
  67. /**
  68. * Render an exception into an HTTP response.
  69. *
  70. * @access public
  71. * @param \Exception $e
  72. * @return Response
  73. */
  74. public function render(Exception $e)
  75. {
  76. if ($this->render && $this->render instanceof \Closure) {
  77. $result = call_user_func_array($this->render, [$e]);
  78. if ($result) {
  79. return $result;
  80. }
  81. }
  82. if ($e instanceof HttpException) {
  83. return $this->renderHttpException($e);
  84. } else {
  85. return $this->convertExceptionToResponse($e);
  86. }
  87. }
  88. /**
  89. * @access public
  90. * @param Output $output
  91. * @param Exception $e
  92. */
  93. public function renderForConsole(Output $output, Exception $e)
  94. {
  95. if (Container::get('app')->isDebug()) {
  96. $output->setVerbosity(Output::VERBOSITY_DEBUG);
  97. }
  98. $output->renderException($e);
  99. }
  100. /**
  101. * @access protected
  102. * @param HttpException $e
  103. * @return Response
  104. */
  105. protected function renderHttpException(HttpException $e)
  106. {
  107. $status = $e->getStatusCode();
  108. $template = Container::get('app')->config('http_exception_template');
  109. if (!Container::get('app')->isDebug() && !empty($template[$status])) {
  110. return Response::create($template[$status], 'view', $status)->assign(['e' => $e]);
  111. } else {
  112. return $this->convertExceptionToResponse($e);
  113. }
  114. }
  115. /**
  116. * @access protected
  117. * @param Exception $exception
  118. * @return Response
  119. */
  120. protected function convertExceptionToResponse(Exception $exception)
  121. {
  122. // 收集异常数据
  123. if (Container::get('app')->isDebug()) {
  124. // 调试模式,获取详细的错误信息
  125. $data = [
  126. 'name' => get_class($exception),
  127. 'file' => $exception->getFile(),
  128. 'line' => $exception->getLine(),
  129. 'message' => $this->getMessage($exception),
  130. 'trace' => $exception->getTrace(),
  131. 'code' => $this->getCode($exception),
  132. 'source' => $this->getSourceCode($exception),
  133. 'datas' => $this->getExtendData($exception),
  134. 'tables' => [
  135. 'GET Data' => $_GET,
  136. 'POST Data' => $_POST,
  137. 'Files' => $_FILES,
  138. 'Cookies' => $_COOKIE,
  139. 'Session' => isset($_SESSION) ? $_SESSION : [],
  140. 'Server/Request Data' => $_SERVER,
  141. 'Environment Variables' => $_ENV,
  142. 'ThinkPHP Constants' => $this->getConst(),
  143. ],
  144. ];
  145. } else {
  146. // 部署模式仅显示 Code 和 Message
  147. $data = [
  148. 'code' => $this->getCode($exception),
  149. 'message' => $this->getMessage($exception),
  150. ];
  151. if (!Container::get('app')->config('show_error_msg')) {
  152. // 不显示详细错误信息
  153. $data['message'] = Container::get('app')->config('error_message');
  154. }
  155. }
  156. //保留一层
  157. while (ob_get_level() > 1) {
  158. ob_end_clean();
  159. }
  160. $data['echo'] = ob_get_clean();
  161. ob_start();
  162. extract($data);
  163. include Container::get('app')->config('exception_tmpl');
  164. // 获取并清空缓存
  165. $content = ob_get_clean();
  166. $response = Response::create($content, 'html');
  167. if ($exception instanceof HttpException) {
  168. $statusCode = $exception->getStatusCode();
  169. $response->header($exception->getHeaders());
  170. }
  171. if (!isset($statusCode)) {
  172. $statusCode = 500;
  173. }
  174. $response->code($statusCode);
  175. return $response;
  176. }
  177. /**
  178. * 获取错误编码
  179. * ErrorException则使用错误级别作为错误编码
  180. * @access protected
  181. * @param \Exception $exception
  182. * @return integer 错误编码
  183. */
  184. protected function getCode(Exception $exception)
  185. {
  186. $code = $exception->getCode();
  187. if (!$code && $exception instanceof ErrorException) {
  188. $code = $exception->getSeverity();
  189. }
  190. return $code;
  191. }
  192. /**
  193. * 获取错误信息
  194. * ErrorException则使用错误级别作为错误编码
  195. * @access protected
  196. * @param \Exception $exception
  197. * @return string 错误信息
  198. */
  199. protected function getMessage(Exception $exception)
  200. {
  201. $message = $exception->getMessage();
  202. if (PHP_SAPI == 'cli') {
  203. return $message;
  204. }
  205. $lang = Container::get('lang');
  206. if (strpos($message, ':')) {
  207. $name = strstr($message, ':', true);
  208. $message = $lang->has($name) ? $lang->get($name) . strstr($message, ':') : $message;
  209. } elseif (strpos($message, ',')) {
  210. $name = strstr($message, ',', true);
  211. $message = $lang->has($name) ? $lang->get($name) . ':' . substr(strstr($message, ','), 1) : $message;
  212. } elseif ($lang->has($message)) {
  213. $message = $lang->get($message);
  214. }
  215. return $message;
  216. }
  217. /**
  218. * 获取出错文件内容
  219. * 获取错误的前9行和后9行
  220. * @access protected
  221. * @param \Exception $exception
  222. * @return array 错误文件内容
  223. */
  224. protected function getSourceCode(Exception $exception)
  225. {
  226. // 读取前9行和后9行
  227. $line = $exception->getLine();
  228. $first = ($line - 9 > 0) ? $line - 9 : 1;
  229. try {
  230. $contents = file($exception->getFile());
  231. $source = [
  232. 'first' => $first,
  233. 'source' => array_slice($contents, $first - 1, 19),
  234. ];
  235. } catch (Exception $e) {
  236. $source = [];
  237. }
  238. return $source;
  239. }
  240. /**
  241. * 获取异常扩展信息
  242. * 用于非调试模式html返回类型显示
  243. * @access protected
  244. * @param \Exception $exception
  245. * @return array 异常类定义的扩展数据
  246. */
  247. protected function getExtendData(Exception $exception)
  248. {
  249. $data = [];
  250. if ($exception instanceof \think\Exception) {
  251. $data = $exception->getData();
  252. }
  253. return $data;
  254. }
  255. /**
  256. * 获取常量列表
  257. * @access private
  258. * @return array 常量列表
  259. */
  260. private static function getConst()
  261. {
  262. $const = get_defined_constants(true);
  263. return isset($const['user']) ? $const['user'] : [];
  264. }
  265. }