Browse Source

7-6api模块自定义错误处理

Home 5 years ago
parent
commit
1d256d2df2
2 changed files with 50 additions and 0 deletions
  1. 42 0
      app/api/exception/Http.php
  2. 8 0
      app/api/provider.php

+ 42 - 0
app/api/exception/Http.php

@@ -0,0 +1,42 @@
+<?php
+/**
+ * Created by PhpStorm
+ * User:林志杰
+ * Email:[email protected]
+ * Motto:纵有疾风起,人生不言弃!
+ * Time:2020/1/13 23:58
+ */
+
+declare(strict_types=1);
+
+namespace app\api\exception;
+
+
+use think\exception\Handle;
+use think\Response;
+use Throwable;
+
+class Http extends Handle
+{
+    public $httpStatus = 500;
+
+    /**
+     * Render an exception into an HTTP response.
+     *
+     * @access public
+     * @param \think\Request $request
+     * @param Throwable $e
+     * @return Response
+     */
+    public function render($request, Throwable $e): Response
+    {
+        if (method_exists($e, "getStatusCode")) {
+            $httpStatus = $e->getStatusCode();
+        } else {
+            $httpStatus = $this->httpStatus;
+        }
+
+        // 自定义异常处理机制
+        return show(config('status.error'), $e->getMessage(), [], $httpStatus);
+    }
+}

+ 8 - 0
app/api/provider.php

@@ -0,0 +1,8 @@
+<?php
+use app\ExceptionHandle;
+use app\Request;
+
+// 容器Provider定义文件
+return [
+    'think\exception\Handle' => app\api\exception\Http::class,
+];