Ver Fonte

fix: 统一处理 API 网关异常,返回x-ca-error-message和x-ca-error-code

runphp há 4 dias atrás
pai
commit
e3138362e4
1 ficheiros alterados com 25 adições e 14 exclusões
  1. 25 14
      src/WuLiuClient.php

+ 25 - 14
src/WuLiuClient.php

@@ -32,19 +32,13 @@ class WuLiuClient
      */
     public function kdi(string $no, string $type = ''): object
     {
-        $response = $this->httpClient->request('GET', 'kdi', [
-            'query' => [
-                'no' => $no,
-                'type' => $type,
-            ]
-        ]);
-        $result = json_decode($response->getContent());
+        $result = $this->request('kdi', ['no' => $no, 'type' => $type]);
+
         if ($result->status == 0) {
             return $result->result;
-        } else {
-            // 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制,错误单号
-            throw_logic_exception($result->msg);
         }
+        // 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制,错误单号
+        throw_logic_exception($result->msg);
     }
 
     /**
@@ -52,12 +46,29 @@ class WuLiuClient
      */
     public function getExpressList(): object
     {
-        $response = $this->httpClient->request('GET', 'getExpressList');
-        $result = json_decode($response->getContent());
+        $result = $this->request('getExpressList');
+
         if ($result->status == 200) {
             return $result->result;
-        } else {
-            throw_logic_exception($result->msg);
+        }
+        throw_logic_exception($result->msg);
+    }
+
+    /**
+     * 发送 HTTP 请求,统一处理 API 网关异常
+     */
+    private function request(string $path, array $query = []): object
+    {
+        try {
+            $response = $this->httpClient->request('GET', $path, ['query' => $query]);
+            return json_decode($response->getContent());
+        } catch (\Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface $e) {
+            $headers = $e->getResponse()->getHeaders(false);
+            throw_logic_exception(
+                $headers['x-ca-error-message'][0] ?? $e->getMessage(),
+                1,
+                $headers['x-ca-error-code'][0] ?? ''
+            );
         }
     }
 }