ExceptionHandle.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace app;
  3. use app\exception\BaseException;
  4. use think\db\exception\DataNotFoundException;
  5. use think\db\exception\ModelNotFoundException;
  6. use think\exception\Handle;
  7. use think\exception\HttpException;
  8. use think\exception\HttpResponseException;
  9. use think\exception\ValidateException;
  10. use think\Response;
  11. use Throwable;
  12. /**
  13. * 应用异常处理类
  14. */
  15. class ExceptionHandle extends Handle
  16. {
  17. /**
  18. * 不需要记录信息(日志)的异常类列表
  19. * @var array
  20. */
  21. protected $ignoreReport = [
  22. HttpException::class,
  23. HttpResponseException::class,
  24. ModelNotFoundException::class,
  25. DataNotFoundException::class,
  26. ValidateException::class,
  27. ];
  28. /**
  29. * 记录异常信息(包括日志或者其它方式记录)
  30. *
  31. * @access public
  32. * @param Throwable $exception
  33. * @return void
  34. */
  35. public function report(Throwable $exception): void
  36. {
  37. // 使用内置的方式记录异常日志
  38. parent::report($exception);
  39. }
  40. /**
  41. * Render an exception into an HTTP response.
  42. *
  43. * @access public
  44. * @param \think\Request $request
  45. * @param Throwable $e
  46. * @return Response
  47. */
  48. public function render($request, Throwable $e): Response
  49. {
  50. // 添加自定义异常处理机制
  51. if($e instanceof BaseException) {
  52. # 自定义异常类
  53. $result = [
  54. 'code' => $e->code,
  55. 'message' => $e->message
  56. ];
  57. return json($result);
  58. }
  59. return parent::render($request, $e);
  60. }
  61. }