Handle.php 9.7 KB

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