ApiExceptionHandle.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace app\api;
  3. use think\exception\DbException;
  4. use think\exception\Handle;
  5. use think\Response;
  6. use Throwable;
  7. class ApiExceptionHandle extends Handle
  8. {
  9. /**
  10. * 记录异常信息(包括日志或者其它方式记录)
  11. *
  12. * @access public
  13. * @param Throwable $exception
  14. * @return void
  15. */
  16. public function report(Throwable $exception): void
  17. {
  18. // 使用内置的方式记录异常日志
  19. parent::report($exception);
  20. }
  21. /**
  22. * Render an exception into an HTTP response.
  23. *
  24. * @access public
  25. * @param \think\Request $request
  26. * @param Throwable $e
  27. * @return Response
  28. */
  29. public function render($request, Throwable $e): Response
  30. {
  31. // 添加自定义异常处理机制
  32. if ($e instanceof DbException) {
  33. return app('json')->fail('数据获取失败');
  34. }
  35. // 其他错误交给系统处理
  36. if (env('APP_DEBUG'))
  37. return parent::render($request, $e);
  38. }
  39. }