傳統「錯誤碼 + 記錄 Log」模式弊端:
if ($r === 'err1') ...)。throw new SpecificException() 即可。try-catch,跨層級零成本。Exception,依類型 catch (DbException $e) / catch (ValidationException $e) 精準處理。$e->getMessage()、getFile()、getLine()、getTrace()、getPrevious()(異常鏈)。// 定義業務異常
class InsufficientStockException extends Exception {}
class PaymentFailedException extends Exception {}
function placeOrder($userId, $items) {
// 庫存檢查
if (!checkStock($items)) throw new InsufficientStockException("庫存不足");
// 支付
if (!chargePayment($userId, $total)) throw new PaymentFailedException("支付失敗");
// 寫入訂單
return createOrder($userId, $items);
}
// 控制器統一捕獲
try {
$order = placeOrder($uid, $cart);
jsonResponse(['ok'=>true, 'order'=>$order]);
} catch (InsufficientStockException $e) {
logWarning($e);
jsonResponse(['ok'=>false, 'code'=>'STOCK', 'msg'=>$e->getMessage()], 400);
} catch (PaymentFailedException $e) {
logError($e);
jsonResponse(['ok'=>false, 'code'=>'PAY', 'msg'=>$e->getMessage()], 402);
} catch (Exception $e) {
logCritical($e); // 未預期錯誤
jsonResponse(['ok'=>false, 'code'=>'SYS', 'msg'=>'系統錯誤'], 500);
}
Exception 結尾,建立層級體系(AppException → DbException/HttpException)。catch 具體類別在前,Exception 兜底在後。display_errors,統一由異常處理器記錄日誌、回傳友善錯誤頁/JSON。Throwable 介面統一 Exception 與 Error,catch (Throwable $e) 可捕獲所有致命錯誤。極簡專案(單檔、無框架)仍可用錯誤碼快速交付。但凡涉及「多模組、團隊協作、長期維護」,異常機制是專業 PHP 開發者的必備基本功。