aexiaoliou 2 lat temu
rodzic
commit
b76b5a17e2

+ 9 - 0
src/exception/CatchException

@@ -0,0 +1,9 @@
+<?php
+
+/**
+ * 应该被捕获器捕获的异常
+ */
+class CatchException extends Exception
+{
+    
+}

+ 35 - 0
src/middleware/AutoResult.php

@@ -0,0 +1,35 @@
+<?php
+
+namespace yckj\commons\middleware;
+
+use Closure;
+use yckj\commons\model\Result;
+use think\Config;
+use think\Request;
+use think\Response;
+use think\Facade\Log;
+
+class AutoResult
+{
+    /**
+     * 自动转化数据为 Result
+     *
+     * @param Request $request
+     * @param Closure $next
+     * 
+     * @return void
+     */
+    public function handle(Request $request, Closure $next)
+    {
+        $response = $next($request);
+
+        $data = $response->getData();
+
+        // 如果已经是 Result 就不动了
+        if ($data instanceof Result) {
+            return $response;
+        }
+
+        return $response->data(Result::of($data));
+    }
+}

+ 26 - 4
src/model/Result.php

@@ -2,15 +2,37 @@
 
 namespace yckj\commons\model;
 
+use CatchException;
+use RuntimeException;
+use think\exception\HttpResponseException;
 use think\Model;
+use think\Facade\Log;
 
-class Result extends Model
+/**
+ * 通用返回值,继承Model是为了方便 \think\Response 序列化对象,这并不是一个数据库对象
+ */
+class Result implements Model
 {
     protected int $code;
 
-    protected string $msg;
-
     protected mixed $data;
-
     
+    protected string $msg = '';
+
+    public function __construct(int $code, $data, $msg = '')
+    {
+        $this->$code = $code;
+        $this->$data = $data;
+        $this->msg = $msg;
+    }
+
+    public static function of($data) 
+    {
+        if(!is_null($data)) {
+            return new Result(0, $data, 'success');
+        }
+
+        Log::error('Unknown Null Error');
+        throw new CatchException('', 1000);
+    }
 }