ExceptionHandle.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace app;
  3. use think\db\exception\DataNotFoundException;
  4. use think\db\exception\ModelNotFoundException;
  5. use think\exception\Handle;
  6. use think\exception\HttpException;
  7. use think\exception\HttpResponseException;
  8. use think\exception\ValidateException;
  9. use think\Response;
  10. use Throwable;
  11. /**
  12. * 应用异常处理类
  13. */
  14. class ExceptionHandle extends Handle {
  15. /**
  16. * 不需要记录信息(日志)的异常类列表
  17. * @var array
  18. */
  19. protected $ignoreReport = [
  20. HttpException::class,
  21. HttpResponseException::class,
  22. ModelNotFoundException::class,
  23. DataNotFoundException::class,
  24. ValidateException::class,
  25. ];
  26. /**
  27. * 记录异常信息(包括日志或者其它方式记录)
  28. *
  29. * @access public
  30. * @param Throwable $exception
  31. * @return void
  32. */
  33. public function report(Throwable $exception): void {
  34. // 使用内置的方式记录异常日志
  35. parent::report($exception);
  36. }
  37. /**
  38. * Render an exception into an HTTP response.
  39. *
  40. * @access public
  41. * @param \think\Request $request
  42. * @param Throwable $e
  43. * @return Response
  44. */
  45. public function render($request, Throwable $e): Response {
  46. // 添加自定义异常处理机制
  47. if ($request->param("backName")) {
  48. //针对现在这个前端界面的特殊的错误返回方式
  49. $index = $request->param("index");
  50. $responseObj = new \stdClass();
  51. $responseObj->obj = $index;
  52. $responseObj->code = 500;
  53. $responseObj->msg = $e->getMessage();
  54. echo \StrUtil::back($responseObj, $request->param("backName"));
  55. exit();
  56. }
  57. // 其他错误交给系统处理
  58. return parent::render($request, $e);
  59. }
  60. }