KefuApiExceptionHandle.php 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\kefuapi;
  12. use crmeb\exceptions\AuthException;
  13. use think\exception\Handle;
  14. use think\exception\ValidateException;
  15. use think\facade\Config;
  16. use think\facade\Log;
  17. use think\Response;
  18. use Throwable;
  19. class KefuApiExceptionHandle extends Handle
  20. {
  21. /**
  22. * 记录异常信息(包括日志或者其它方式记录)
  23. * @access public
  24. * @param Throwable $exception
  25. * @return void
  26. */
  27. public function report(Throwable $exception):void
  28. {
  29. $data = [
  30. 'file' => $exception->getFile(),
  31. 'line' => $exception->getLine(),
  32. 'message' => $this->getMessage($exception),
  33. 'code' => $this->getCode($exception),
  34. ];
  35. //日志内容
  36. $log = [
  37. request()->kefuId(), //客服ID
  38. request()->ip(), //客户ip
  39. ceil(msectime() - (request()->time(true) * 1000)), //耗时(毫秒)
  40. request()->rule()->getMethod(), //请求类型
  41. str_replace("/", "", request()->rootUrl()), //应用
  42. request()->baseUrl(), //路由
  43. json_encode(request()->param(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), //请求参数
  44. json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), //报错数据
  45. ];
  46. Log::write(implode("|", $log), "error");
  47. }
  48. /**
  49. * Render an exception into an HTTP response.
  50. * @access public
  51. * @param \think\Request $request
  52. * @param Throwable $e
  53. * @return Response
  54. */
  55. public function render($request, Throwable $e):Response
  56. {
  57. $massageData = Config::get('app_debug', false) ? [
  58. 'file' => $e->getFile(),
  59. 'line' => $e->getLine(),
  60. 'trace' => $e->getTrace(),
  61. 'previous' => $e->getPrevious(),
  62. ] : [];
  63. // 添加自定义异常处理机制
  64. if ($e instanceof DbException) {
  65. return app('json')->fail('数据获取失败', $massageData);
  66. } elseif ($e instanceof ValidateException || $e instanceof AuthException) {
  67. return app('json')->make($e->getCode() ? : 400, $e->getMessage());
  68. } else {
  69. return app('json')->code(200)->make(400, $e->getMessage(), $massageData);
  70. }
  71. }
  72. }