Browse Source

后台接管报错

lizhen_gitee 4 months ago
parent
commit
98349c903f

+ 1 - 0
application/admin/config.php

@@ -5,4 +5,5 @@ return [
     'url_common_param'       => true,
     'url_html_suffix'        => '',
     'controller_auto_search' => true,
+    'exception_handle'        => '\\app\\admin\\library\\ExceptionHandle',
 ];

+ 46 - 0
application/admin/library/ExceptionHandle.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace app\admin\library;
+
+use Exception;
+use think\exception\Handle;
+
+/**
+ * 自定义API模块的错误显示
+ */
+class ExceptionHandle extends Handle
+{
+
+    public function render(Exception $e)
+    {
+        //return parent::render($e);
+        $statuscode = $code = 500;
+        $msg = $e->getMessage();
+        // 验证异常
+        if ($e instanceof \think\exception\ValidateException) {
+            $code = 0;
+            $statuscode = 200;
+            $msg = $e->getError();
+
+        }
+        // Http异常
+        if ($e instanceof \think\exception\HttpException) {
+            $statuscode = $code = $e->getStatusCode();
+            $msg = $e->getMessage();
+        }
+
+        $result = ['code' => $code, 'msg' => $msg, 'time' => time(), 'data' => null];
+
+
+        //记录app异常返回结果
+        $modulename     = request()->module();
+        $controllername = request()->controller();
+        $actionname     = request()->action();
+
+        db('admin_request_log')->insert(['api'   => $modulename.'/'.$controllername.'/'.$actionname,'params'=>json_encode(request()->request()), 'result'=>json_encode($result)]);
+
+
+        return json($result, $statuscode);
+    }
+
+}

+ 16 - 0
application/common/controller/Backend.php

@@ -12,6 +12,8 @@ use think\Model;
 use think\Session;
 use fast\Tree;
 use think\Validate;
+use think\exception\HttpResponseException;
+use think\Response;
 
 /**
  * 后台控制器基类
@@ -740,4 +742,18 @@ class Backend extends Controller
         //刷新Token
         $this->request->token();
     }
+
+    protected function result($data, $code = 0, $msg = '', $type = '', array $header = [])
+    {
+        $result = [
+            'code' => $code,
+            'msg'  => $msg,
+            'time' => $this->request->server('REQUEST_TIME'),
+            'data' => $data,
+        ];
+        $type     = $type ?: $this->getResponseType();
+        $response = Response::create($result, $type)->header($header);
+
+        throw new HttpResponseException($response);
+    }
 }