參考淘寶、微博等大型開放平台的錯誤碼規範,建立統一的 JSON 錯誤回應結構,提升前後端協作效率。本文示範使用抽象工廠模式實作錯誤訊息產生器,支援多語言包與錯誤碼映射。
{
"error": {
"name": "Not Found",
"message": "操作失敗",
"error_code": "20003"
}
}
Error($_errors, $code) 方法。Msg() 回傳 Hint 實例。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),拋出例外由全域異常處理器統一格式化輸出;錯誤碼定義於常數類別或設定檔。