经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
Thinkphp 在api开发中异常返回依然是html的解决方式
来源:jb51  时间:2019/10/17 9:05:30  对本文有异议

现在谁不开发接口的呢?但是在接口开发过程中,报错误异常后居然返回错误的信息依然是html信息!TP官方也不知道为啥不添加,说好的为接口而生,我的解决方案也很简单,把系统的异常处理类复制出来,去掉模板相关,直接以json方式输出

下面是解决方案:

1:按照TP扩展异常的方式引用这个文件

https://www.kancloud.cn/manual/thinkphp5_1/354092

  1. // 判断默认输出类型
  2. // $app 是配置数组
  3. if ($app['default_return_type'] == 'json') {
  4. // 异常处理handle类 留空使用 \think\exception\Handle
  5. $app['exception_handle'] = '\\app\\common\\exception\\JsonException';
  6. }
  7. return $app;

异常处理类:

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

以上这篇Thinkphp 在api开发中异常返回依然是html的解决方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号