ExceptionHandle.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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\facade\View;
  11. use think\Response;
  12. use think\template\exception\TemplateNotFoundException;
  13. use Throwable;
  14. /**
  15. * 应用异常处理类
  16. */
  17. class ExceptionHandle extends Handle
  18. {
  19. /**
  20. * 不需要记录信息(日志)的异常类列表
  21. * @var array
  22. */
  23. protected $ignoreReport = [
  24. HttpException::class,
  25. HttpResponseException::class,
  26. ModelNotFoundException::class,
  27. DataNotFoundException::class,
  28. ValidateException::class,
  29. ];
  30. /**
  31. * 记录异常信息(包括日志或者其它方式记录)
  32. *
  33. * @access public
  34. * @param Throwable $exception
  35. * @return void
  36. */
  37. public function report(Throwable $exception): void
  38. {
  39. // 使用内置的方式记录异常日志
  40. parent::report($exception);
  41. }
  42. /**
  43. * @param \think\Request $request
  44. * @param Throwable $e
  45. * @return Response
  46. * @throws \Exception
  47. */
  48. public function render($request, Throwable $e): Response
  49. {
  50. // 请求异常
  51. if (!env('app_debug') && ($request->post()||$request->isAjax())) {
  52. $data = [
  53. 'code' => -1,
  54. 'message' => "系统异常:".$e->getMessage(),
  55. 'timestamp' => time()
  56. ];
  57. return json($data);
  58. }elseif($e instanceof HttpException){
  59. return view(app()->getRootPath() . 'public/error/error.html');
  60. }
  61. // 其他错误交给系统处理
  62. return parent::render($request, $e);
  63. }
  64. }