ApiExceptionHandle.php 2.3 KB

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