ExceptionHandle.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace app;
  3. use think\db\exception\DataNotFoundException;
  4. use think\db\exception\ModelNotFoundException;
  5. use think\db\exception\PDOException;
  6. use think\exception\ErrorException;
  7. use think\exception\Handle;
  8. use think\exception\HttpException;
  9. use think\exception\HttpResponseException;
  10. use think\exception\ValidateException;
  11. use think\Response;
  12. use Throwable;
  13. /**
  14. * 应用异常处理类
  15. */
  16. class ExceptionHandle extends Handle
  17. {
  18. /**
  19. * 不需要记录信息(日志)的异常类列表
  20. * @var array
  21. */
  22. protected $ignoreReport = [
  23. HttpException::class,
  24. HttpResponseException::class,
  25. ModelNotFoundException::class,
  26. DataNotFoundException::class,
  27. ValidateException::class,
  28. ];
  29. /**
  30. * 记录异常信息(包括日志或者其它方式记录)
  31. *
  32. * @access public
  33. * @param Throwable $exception
  34. * @return void
  35. */
  36. public function report(Throwable $exception): void
  37. {
  38. // 使用内置的方式记录异常日志
  39. parent::report($exception);
  40. }
  41. /**
  42. * Render an exception into an HTTP response.
  43. *
  44. * @access public
  45. * @param \think\Request $request
  46. * @param Throwable $e
  47. * @return Response
  48. */
  49. public function render($request, Throwable $e): Response
  50. {
  51. // 添加自定义异常处理机制
  52. $this->report($e);
  53. // 其他错误交给系统处理
  54. if ($e instanceof ValidateException)
  55. return app('json')->fail($e->getMessage());
  56. else if ($e instanceof DataNotFoundException)
  57. return app('json')->fail(isDebug() ? $e->getMessage() : '数据不存在');
  58. else if ($e instanceof ModelNotFoundException)
  59. return app('json')->fail(isDebug() ? $e->getMessage() : '数据不存在');
  60. else if ($e instanceof PDOException)
  61. return app('json')->fail(isDebug() ? $e->getMessage() : '数据库操作失败', isDebug() ? $e->getData() : []);
  62. else if ($e instanceof ErrorException)
  63. return app('json')->fail(isDebug() ? $e->getMessage() : '系统错误', isDebug() ? $e->getData() : []);
  64. else if ($e instanceof \PDOException)
  65. return app('json')->fail(isDebug() ? $e->getMessage() : '数据库连接失败');
  66. else if ($e instanceof \EasyWeChat\Core\Exceptions\HttpException)
  67. return app('json')->fail($e->getMessage());
  68. return parent::render($request, $e);
  69. }
  70. }