ApiExceptionHandle.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace app\api;
  3. use crmeb\exceptions\SiteException;
  4. use crmeb\exceptions\UtilException;
  5. use think\db\exception\DbException;
  6. use think\exception\Handle;
  7. use think\Response;
  8. use Throwable;
  9. class ApiExceptionHandle extends Handle
  10. {
  11. /**
  12. * 记录异常信息(包括日志或者其它方式记录)
  13. *
  14. * @access public
  15. * @param Throwable $exception
  16. * @return void
  17. */
  18. public function report(Throwable $exception): void
  19. {
  20. // 使用内置的方式记录异常日志
  21. parent::report($exception);
  22. }
  23. /**
  24. * Render an exception into an HTTP response.
  25. *
  26. * @access public
  27. * @param \think\Request $request
  28. * @param Throwable $e
  29. * @return Response
  30. */
  31. public function render($request, Throwable $e): Response
  32. {
  33. // 添加自定义异常处理机制
  34. if ($e instanceof DbException) {
  35. return app('json')->fail('数据获取失败', [
  36. 'file' => $e->getFile(),
  37. 'message' => $e->getMessage(),
  38. 'line' => $e->getLine(),
  39. 'trace' => $e->getTrace(),
  40. ]);
  41. } elseif ($e instanceof SiteException || $e instanceof UtilException) {
  42. return app('json')->fail($e->getMessage());
  43. } else {
  44. // return app('json')->fail('系统出现异常', [
  45. // 'message' => $e->getMessage(),
  46. // 'file' => $e->getFile(),
  47. // 'code' => $e->getCode(),
  48. // 'line' => $e->getLine(),
  49. // 'trace' => $e->getTrace(),
  50. // 'previous' => $e->getPrevious(),
  51. // ]);
  52. return app('json')->fail($e->getMessage());
  53. }
  54. }
  55. }