KefuApiExceptionHandle.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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\Response;
  17. use Throwable;
  18. class KefuApiExceptionHandle extends Handle
  19. {
  20. /**
  21. * 记录异常信息(包括日志或者其它方式记录)
  22. *
  23. * @access public
  24. * @param Throwable $exception
  25. * @return void
  26. */
  27. public function report(Throwable $exception): void
  28. {
  29. // 使用内置的方式记录异常日志
  30. parent::report($exception);
  31. }
  32. /**
  33. * Render an exception into an HTTP response.
  34. *
  35. * @access public
  36. * @param \think\Request $request
  37. * @param Throwable $e
  38. * @return Response
  39. */
  40. public function render($request, Throwable $e): Response
  41. {
  42. $massageData = Config::get('app_debug', false) ? [
  43. 'file' => $e->getFile(),
  44. 'line' => $e->getLine(),
  45. 'trace' => $e->getTrace(),
  46. 'previous' => $e->getPrevious(),
  47. ] : [];
  48. // 添加自定义异常处理机制
  49. if ($e instanceof DbException) {
  50. return app('json')->fail('数据获取失败', $massageData);
  51. } elseif ($e instanceof ValidateException || $e instanceof AuthException) {
  52. return app('json')->make($e->getCode() ?: 400, $e->getMessage());
  53. } else {
  54. return app('json')->code(200)->make(400, $e->getMessage(), $massageData);
  55. }
  56. }
  57. }