AdminApiExceptionHandle.php 1.7 KB

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