異常處理是現代 PHP 應用健壯性的基石。從 PHP 5 引入 Exception 到 PHP 8 新增 Throwable 介面、ValueError、UnhandledMatchError 等,異常體系日趨完善。本文系統解析 try-catch 流程、自訂異常體系、全域處理器、錯誤轉異常、測試策略與生產環境最佳實踐。
Throwable (介面)
├── Exception (基礎例外類別)
│ ├── ErrorException // 錯誤轉異常
│ ├── RuntimeException // 執行期錯誤 (邏輯、IO、外部服務)
│ │ ├── OverflowException
│ │ ├── UnderflowException
│ │ └── ...
│ ├── LogicException // 程式邏輯錯誤 (前置條件違反)
│ │ ├── InvalidArgumentException
│ │ ├── LengthException
│ │ └── ...
│ └── ... (SPL 內建異常)
├── Error (PHP 內部錯誤,PHP 7+)
│ ├── TypeError // 型別不符
│ ├── ValueError // 數值範圍錯誤 (PHP 8+)
│ ├── ParseError // 編譯錯誤
│ └── AssertionError // assert() 失敗
<?php
function readConfig(string $path): array {
try {
// 可能拋出異常的程式碼
if (!file_exists($path)) {
throw new RuntimeException("配置檔不存在:$path");
}
$content = file_get_contents($path);
if ($content === false) {
throw new RuntimeException("無法讀取檔案:$path");
}
$config = json_decode($content, true, 512, JSON_THROW_ON_ERROR); // PHP 7.3+ 拋出 JsonException
return $config;
} catch (JsonException $e) {
// 具體異常優先捕獲
throw new RuntimeException("JSON 解析失敗:{$e->getMessage()}", 0, $e); // 異常鏈
} catch (RuntimeException $e) {
// 記錄日誌
error_log("Config 讀取失敗:{$e->getMessage()}", 3, '/var/log/app.log');
throw $e; // 重新拋出讓上層處理
} finally {
// 無論是否拋出異常都會執行 (return 前也會執行)
// 適合釋放資源:關閉檔案、釋放鎖、清理暫存
}
}
<?php
try {
riskyOperation();
} catch (ValidationException $e) { // 1. 最具體的先捕獲
// 處理驗證錯誤
} catch (AuthenticationException $e) { // 2. 業務異常
// 導向登入
} catch (RuntimeException $e) { // 3. 通用執行期異常
// 記錄、回應 500
} catch (Throwable $e) { // 4. 最後捕獲所有 (含 Error)
// 記錄嚴重錯誤、發送警報
// 不要吞沒 Error (如 TypeError),應重新拋出或記錄後終止
}
<?php
// 基礎業務異常
abstract class AppException extends Exception {
public function __construct(
string $message = '',
public readonly int $code = 0,
public readonly string $errorCode = '', // 業務錯誤碼 (如 USER_NOT_FOUND)
?Throwable $previous = null
) {
parent::__construct($message, $code, $previous);
}
public function toArray(): array {
return [
'error' => $this->errorCode ?: get_class($this),
'message' => $this->getMessage(),
'code' => $this->code,
'trace' => $this->getTraceAsString(),
];
}
}
// 具體異常
class UserNotFoundException extends AppException {
public function __construct(string $identifier, ?Throwable $previous = null) {
parent::__construct("使用者不存在:$identifier", 404, 'USER_NOT_FOUND', $previous);
}
}
class InsufficientBalanceException extends AppException {
public function __construct(
public readonly float $current,
public readonly float $required,
?Throwable $previous = null
) {
parent::__construct(
"餘額不足:目前 {$current},需求 {$required}",
400,
'INSUFFICIENT_BALANCE',
$previous
);
}
}
// 使用
try {
$user = $userRepo->findById($id) ?? throw new UserNotFoundException($id);
if ($user->balance < $amount) {
throw new InsufficientBalanceException($user->balance, $amount);
}
} catch (AppException $e) {
// 統一錯誤回應格式
http_response_code($e->code);
echo json_encode($e->toArray());
}
<?php
// 僅適用於未被 catch 捕獲的異常 (頂層)
set_exception_handler(function (Throwable $e) {
// 1. 記錄完整堆疊
error_log("未捕獲異常:{$e->getMessage()}\n{$e->getTraceAsString()}");
// 2. 非生產環境顯示詳情
if (($_ENV['APP_DEBUG'] ?? false)) {
echo "Uncaught Exception
";
echo "{$e->getMessage()}\n{$e->getTraceAsString()}";
} else {
// 生產環境:友善錯誤頁
http_response_code(500);
include __DIR__ . '/templates/500.php';
}
});
// 關鍵:關閉 display_errors,避免洩漏敏感資訊
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php_errors.log');
<?php
// 將 PHP 錯誤 (Warning, Notice 等) 轉為異常,統一由 try-catch 處理
set_error_handler(function (int $severity, string $message, string $file, int $line): bool {
// 忽略被 @ 抑制的錯誤
if (error_reporting() === 0) return false;
// 只轉換嚴重錯誤 (可自訂)
if (!in_array($severity, [E_WARNING, E_NOTICE, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE, E_DEPRECATED, E_USER_DEPRECATED], true)) {
return false; // 交給 PHP 內建處理
}
throw new ErrorException($message, 0, $severity, $file, $line);
});
// 現在可以 catch 警告!
try {
$content = @file_get_contents('not_exist.txt'); // @ 抑制警告
if ($content === false) throw new RuntimeException('讀取失敗');
} catch (ErrorException $e) {
// 捕獲到被轉換的警告
} catch (RuntimeException $e) {
// 我們主動拋出的
}
ValueError:參數值合法型別但範圍不合法 (如 json_decode('', depth: -1))。UnhandledMatchError:match 表達式無分支匹配且無 default。FiberError:Fiber 協程相關錯誤。ArgumentCountError、TypeError 繼承自 Error,不再是 Exception。<?php
// PHPUnit 範例
use PHPUnit\Framework\TestCase;
class PaymentTest extends TestCase {
public function testInsufficientBalanceThrowsException(): void {
$service = new PaymentService();
// 斷言拋出特定異常
$this->expectException(InsufficientBalanceException::class);
$this->expectExceptionCode(400);
$this->expectExceptionMessageMatches('/餘額不足/');
// 也可檢查自訂屬性 (需自訂斷言)
$service->pay(1001, 5000); // 餘額 1000
}
public function testExceptionChaining(): void {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('JSON 解析失敗');
// 檢查 previous 異常
try {
$service->loadConfig('bad.json');
} catch (RuntimeException $e) {
$this->assertInstanceOf(JsonException::class, $e->getPrevious());
throw $e;
}
}
}
catch (Exception $e) { /* 空 */ } 是大忌,至少記錄日誌。throw new AppException(..., 0, $e) 保留原始堆疊。{"error":"CODE","message":"...","details":{}},前端統一處理。null/false/Option 型別處理正常流程。異常處理不是「寫 catch 就好」,而是設計清晰的異常層級、統一的錯誤回應、完善的日誌監控、可測試的錯誤路徑。建立專案專屬的異常體系,讓錯誤可見、可控、可追蹤!