AdminApiExceptionHandle.php 2.3 KB

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