ExceptionHandle.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. namespace app;
  3. use app\model\CommonModel;
  4. use think\db\exception\DataNotFoundException;
  5. use think\db\exception\ModelNotFoundException;
  6. use think\Exception;
  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. if ($e instanceof ValidateException) return json_show(CommonModel::$error_param, $e->getError());
  53. elseif ($e instanceof Exception) return json_show(CommonModel::$error_default, $e->getMessage());
  54. else return json_show(CommonModel::$error_other, $e->getMessage());//return parent::render($request, $e);// 其他错误交给系统处理
  55. }
  56. }