ExceptionHandle.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * 统一异常接管
  4. */
  5. namespace app;
  6. use think\db\exception\DataNotFoundException;
  7. use think\db\exception\ModelNotFoundException;
  8. use think\exception\FuncNotFoundException;
  9. use think\exception\ClassNotFoundException;
  10. use think\exception\ErrorException;
  11. use think\exception\Handle;
  12. use think\exception\HttpException;
  13. use think\exception\HttpResponseException;
  14. use think\exception\ValidateException;
  15. use think\template\exception\TemplateNotFoundException;
  16. use think\db\exception\PDOException;
  17. use think\db\exception\DbException;
  18. use think\Response;
  19. use Throwable;
  20. use think\facade\Log;
  21. use RuntimeException;
  22. /**
  23. * 应用异常处理类
  24. */
  25. class ExceptionHandle extends Handle
  26. {
  27. private $error_log_db = true; //异常日志是否写入数据库
  28. /**
  29. * Render an exception into an HTTP response.
  30. * @access public
  31. * @param \think\Request $request
  32. * @param Throwable $e
  33. * @return Response
  34. */
  35. public function render($request, Throwable $e): Response
  36. {
  37. //方法不存在
  38. if ($e instanceof FuncNotFoundException) {
  39. if($request->isAjax()){
  40. return json(['status'=>404,'msg'=>$e->getFunc().'方法不存在']);
  41. }else{
  42. return response($e->getFunc().'控制器不存在', 404);
  43. }
  44. }
  45. //控制器不存在
  46. if ($e instanceof ClassNotFoundException) {
  47. if($request->isAjax()){
  48. return json(['status'=>404,'msg'=>$e->getClass().'控制器不存在']);
  49. }else{
  50. return response($e->getClass().'控制器不存在', 404);
  51. }
  52. }
  53. //模板不存在
  54. if ($e instanceof TemplateNotFoundException) {
  55. return response($e->getTemplate().'模板不存在', 404);
  56. }
  57. //验证器异常
  58. if ($e instanceof ValidateException) {
  59. return json(['status'=>411,'msg'=>$e->getError()]);
  60. }
  61. //pdo异常
  62. if ($e instanceof PDOException) {
  63. return response($e->getMessage(), 500);
  64. }
  65. //db异常
  66. if ($e instanceof DbException) {
  67. return response($e->getMessage(), 500);
  68. }
  69. //error系统层面错误异常
  70. if ($e instanceof ErrorException) {
  71. return response($e->getMessage(), 500);
  72. }
  73. // 请求异常 多为自定义的请求异常
  74. if ($e instanceof HttpException) {
  75. Log::error('错误信息:'.print_r($e->getMessage(),true));
  76. if($e->getStatusCode() == 500 && $this->error_log_db){
  77. event('ExceptionLog', $e->getMessage());
  78. }
  79. return json(['status'=>$e->getStatusCode(),'msg'=>$e->getMessage()]);
  80. }
  81. return parent::render($request, $e);
  82. }
  83. }