Handle.php 8.4 KB

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