ApiExceptionHandle.php 1.5 KB

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