首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

RESTful API 統一錯誤回應格式實作:採用抽象工廠模式

     編輯:PHP 相關知識

RESTful API 統一錯誤回應格式實作:採用抽象工廠模式

參考淘寶、微博等大型開放平台的錯誤碼規範,建立統一的 JSON 錯誤回應結構,提升前後端協作效率。本文示範使用抽象工廠模式實作錯誤訊息產生器,支援多語言包與錯誤碼映射。

目標回應格式

{
  "error": {
    "name": "Not Found",
    "message": "操作失敗",
    "error_code": "20003"
  }
}

類別架構

  1. Hint 介面:定義 Error($_errors, $code) 方法。
  2. Template 類別:實作 Hint,定義 JSON 輸出格式。
  3. createMsg 介面:工廠方法 Msg() 回傳 Hint 實例。
  4. FactoryMsg 類別:實作 createMsg,回傳 new Template()。
  5. ErrorMsg 類別:靜態方法 Info($_errors),根據錯誤訊息關鍵字映射錯誤碼,呼叫工廠輸出。

核心程式碼

// common/hint/error/Hint.php
interface Hint { public function Error($_errors, $code); }

// common/hint/error/Template.php
class Template implements Hint {
    public function Error($_errors, $code) {
        if (empty($_errors)) { print_r(json_encode([])); }
        else {
            $errors['error']['name'] = 'Not Found';
            $errors['error']['message'] = $_errors;
            $errors['error']['error_code'] = $code;
            print_r(json_encode($errors));
        }
    }
}

// common/hint/error/createMsg.php
interface createMsg { public function Msg(); }

// common/hint/error/FactoryMsg.php
class FactoryMsg implements createMsg {
    public function Msg() { return new Template; }
}

// common/hint/error/ErrorMsg.php
class ErrorMsg {
    public static function Info($_errors) {
        $Factory = new FactoryMsg;
        // 使用語言包 Yii::t() 取得多語言錯誤訊息
        $result  = strstr($_errors, Yii::t('yii','Not exist')); // 20001
        $result1 = strstr($_errors, Yii::t('yii','Null'));      // 20002
        $result2 = strstr($_errors, Yii::t('yii','Fail'));      // 20003
        $result3 = strstr($_errors, Yii::t('yii','Not right')); // 20004
        $result4 = strstr($_errors, Yii::t('yii','Robc'));      // 20005

        if(!empty($result))  { $M=$Factory->Msg(); $M->Error($_errors,'20001'); die; }
        if(!empty($result1)) { $M=$Factory->Msg(); $M->Error($_errors,'20002'); die; }
        if(!empty($result2)) { $M=$Factory->Msg(); $M->Error($_errors,'20003'); die; }
        if(!empty($result3)) { $M=$Factory->Msg(); $M->Error($_errors,'20004'); die; }
        if(!empty($result4)) { $M=$Factory->Msg(); $M->Error($_errors,'20005'); die; }
        // 預設錯誤碼
        $M=$Factory->Msg(); $M->Error($_errors,'21000');
    }
}

控制器調用方式

use common\hint\error\ErrorMsg;
ErrorMsg::Info(Yii::t('yii','failure'));

優缺點分析與改進方向

  • 優點:結構清晰、易擴展、支援多語言包。
  • 缺點:strstr 關鍵字匹配過於寬鬆,易誤判;錯誤碼映射硬編碼於 ErrorMsg 中,維護不便。
  • 建議改進:改用例外類別層級對應錯誤碼(如 NotFoundException → 20001),拋出例外由全域異常處理器統一格式化輸出;錯誤碼定義於常數類別或設定檔。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved