介紹 (Introduction)
當你開始一個新的 Laravel 專案時,錯誤和例外處理已經為你設定好了;然而,在任何時候,你都可以在應用程式的 bootstrap/app.php 中使用 withExceptions 方法來管理例外如何被回報和渲染。
提供給 withExceptions 閉包的 $exceptions 物件是 Illuminate\Foundation\Configuration\Exceptions 的實例,負責管理應用程式中的例外處理。我們將在這份文件中深入探討這個物件。
設定 (Configuration)
config/app.php 設定檔中的 debug 選項決定了向使用者實際顯示多少關於錯誤的資訊。預設情況下,此選項會遵循儲存在 .env 檔案中的 APP_DEBUG 環境變數的值。
在本地開發期間,你應該將 APP_DEBUG 環境變數設定為 true。在你的正式環境中,此值應始終為 false。如果在正式環境中將該值設定為 true,你會有將敏感設定值暴露給應用程式終端使用者的風險。
處理例外 (Handling Exceptions)
回報例外 (Reporting Exceptions)
在 Laravel 中,例外回報用於記錄例外或將它們發送到外部服務,如 Sentry 或 Flare。預設情況下,例外會根據你的日誌設定進行記錄。然而,你可以自由地以任何方式記錄例外。
如果你需要以不同方式回報不同類型的例外,你可以在應用程式的 bootstrap/app.php 中使用 report 例外方法來註冊一個當需要回報特定類型的例外時應該執行的閉包。Laravel 會透過檢查閉包的類型提示來判斷閉包回報的例外類型:
use App\Exceptions\InvalidOrderException;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->report(function (InvalidOrderException $e) {
// ...
});
})
當你使用 report 方法註冊自訂例外回報回呼時,Laravel 仍然會使用應用程式的預設日誌設定來記錄例外。如果你希望停止例外傳播到預設日誌堆疊,你可以在定義回報回呼時使用 stop 方法,或從回呼中回傳 false:
use App\Exceptions\InvalidOrderException;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->report(function (InvalidOrderException $e) {
// ...
})->stop();
$exceptions->report(function (InvalidOrderException $e) {
return false;
});
})
[!NOTE] 要自訂特定例外的例外回報,你也可以使用可回報例外。
全域日誌上下文 (Global Log Context)
如果可用,Laravel 會自動將當前使用者的 ID 作為上下文資料新增到每個例外的日誌訊息中。你可以在應用程式的 bootstrap/app.php 檔案中使用 context 例外方法來定義你自己的全域上下文資料。這些資訊將包含在你應用程式寫入的每個例外日誌訊息中:
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->context(fn () => [
'foo' => 'bar',
]);
})
例外日誌上下文 (Exception Log Context)
雖然在每個日誌訊息中新增上下文可能很有用,但有時特定例外可能具有你想要包含在日誌中的獨特上下文。透過在應用程式的其中一個例外上定義 context 方法,你可以指定與該例外相關的任何資料,這些資料應該新增到例外的日誌條目中:
<?php
namespace App\Exceptions;
use Exception;
class InvalidOrderException extends Exception
{
// ...
/**
* Get the exception's context information.
*
* @return array<string, mixed>
*/
public function context(): array
{
return ['order_id' => $this->orderId];
}
}
report 輔助函式 (The Report Helper)
有時你可能需要回報例外但繼續處理當前請求。report 輔助函式允許你快速回報例外,而不向使用者渲染錯誤頁面:
public function isValid(string $value): bool
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
去重回報的例外 (Deduplicating Reported Exceptions)
如果你在整個應用程式中使用 report 函式,你可能偶爾會多次回報相同的例外,在日誌中建立重複的條目。
如果你想要確保單一例外實例只會被回報一次,你可以在應用程式的 bootstrap/app.php 檔案中調用 dontReportDuplicates 例外方法:
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->dontReportDuplicates();
})
現在,當使用相同例外實例呼叫 report 輔助函式時,只有第一次呼叫會被回報:
$original = new RuntimeException('Whoops!');
report($original); // reported
try {
throw $original;
} catch (Throwable $caught) {
report($caught); // ignored
}
report($original); // ignored
report($caught); // ignored
例外日誌層級 (Exception Log Levels)
當訊息寫入應用程式的日誌時,訊息會以指定的日誌層級寫入,表示被記錄訊息的嚴重性或重要性。
如上所述,即使你使用 report 方法註冊自訂例外回報回呼,Laravel 仍然會使用應用程式的預設日誌設定來記錄例外;然而,由於日誌層級有時會影響訊息記錄到哪些通道,你可能希望設定某些例外記錄的日誌層級。
為達成此目的,你可以在應用程式的 bootstrap/app.php 檔案中使用 level 例外方法。此方法接收例外類型作為第一個引數,日誌層級作為第二個引數:
use PDOException;
use Psr\Log\LogLevel;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->level(PDOException::class, LogLevel::CRITICAL);
})
依類型忽略例外 (Ignoring Exceptions By Type)
在建構應用程式時,會有一些類型的例外是你永遠不想回報的。要忽略這些例外,你可以在應用程式的 bootstrap/app.php 檔案中使用 dontReport 例外方法。提供給此方法的任何類別都永遠不會被回報;然而,它們仍然可能具有自訂渲染邏輯:
use App\Exceptions\InvalidOrderException;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->dontReport([
InvalidOrderException::class,
]);
})
或者,你可以簡單地使用 Illuminate\Contracts\Debug\ShouldntReport 介面「標記」例外類別。當例外被標記此介面時,Laravel 的例外處理器永遠不會回報它:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Contracts\Debug\ShouldntReport;
class PodcastProcessingException extends Exception implements ShouldntReport
{
//
}
如果你需要更精細地控制何時忽略特定類型的例外,你可以提供一個閉包給 dontReportWhen 方法:
use App\Exceptions\InvalidOrderException;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->dontReportWhen(function (Throwable $e) {
return $e instanceof PodcastProcessingException &&
$e->reason() === 'Subscription expired';
});
})
在內部,Laravel 已經為你忽略了某些類型的錯誤,例如來自 404 HTTP 錯誤或無效 CSRF 權杖產生的 419 HTTP 回應的例外。如果你想要指示 Laravel 停止忽略特定類型的例外,你可以在應用程式的 bootstrap/app.php 檔案中使用 stopIgnoring 例外方法:
use Symfony\Component\HttpKernel\Exception\HttpException;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->stopIgnoring(HttpException::class);
})
渲染例外 (Rendering Exceptions)
預設情況下,Laravel 例外處理器會將例外轉換為 HTTP 回應。然而,你可以自由地為特定類型的例外註冊自訂渲染閉包。你可以透過在應用程式的 bootstrap/app.php 檔案中使用 render 例外方法來完成此操作。
傳遞給 render 方法的閉包應該回傳一個 Illuminate\Http\Response 實例,可以透過 response 輔助函式產生。Laravel 會透過檢查閉包的類型提示來判斷閉包渲染的例外類型:
use App\Exceptions\InvalidOrderException;
use Illuminate\Http\Request;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (InvalidOrderException $e, Request $request) {
return response()->view('errors.invalid-order', status: 500);
});
})
你也可以使用 render 方法來覆蓋內建 Laravel 或 Symfony 例外(如 NotFoundHttpException)的渲染行為。如果提供給 render 方法的閉包沒有回傳值,Laravel 的預設例外渲染將被使用:
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->render(function (NotFoundHttpException $e, Request $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => 'Record not found.'
], 404);
}
});
})
將例外渲染為 JSON (Rendering Exceptions As Json)
渲染例外時,Laravel 會根據請求的 Accept 標頭自動判斷例外應該渲染為 HTML 還是 JSON 回應。如果你想自訂 Laravel 如何判斷要渲染 HTML 還是 JSON 例外回應,你可以使用 shouldRenderJsonWhen 方法:
use Illuminate\Http\Request;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('admin/*')) {
return true;
}
return $request->expectsJson();
});
})
自訂例外回應 (Customizing The Exception Response)
極少數情況下,你可能需要自訂 Laravel 例外處理器渲染的整個 HTTP 回應。為達成此目的,你可以使用 respond 方法註冊回應自訂閉包:
use Symfony\Component\HttpFoundation\Response;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->respond(function (Response $response) {
if ($response->getStatusCode() === 419) {
return back()->with([
'message' => 'The page expired, please try again.',
]);
}
return $response;
});
})
可回報和可渲染的例外 (Renderable Exceptions)
與其在應用程式的 bootstrap/app.php 檔案中定義自訂回報和渲染行為,你可以直接在應用程式的例外上定義 report 和 render 方法。當這些方法存在時,框架會自動呼叫它們:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class InvalidOrderException extends Exception
{
/**
* Report the exception.
*/
public function report(): void
{
// ...
}
/**
* Render the exception as an HTTP response.
*/
public function render(Request $request): Response
{
return response(/* ... */);
}
}
如果你的例外繼承自一個已經可渲染的例外,例如內建的 Laravel 或 Symfony 例外,你可以從例外的 render 方法中回傳 false 來渲染例外的預設 HTTP 回應:
/**
* Render the exception as an HTTP response.
*/
public function render(Request $request): Response|bool
{
if (/** Determine if the exception needs custom rendering */) {
return response(/* ... */);
}
return false;
}
如果你的例外包含只在某些條件滿足時才需要的自訂回報邏輯,你可能需要指示 Laravel 有時使用預設例外處理設定來回報例外。為達成此目的,你可以從例外的 report 方法中回傳 false:
/**
* Report the exception.
*/
public function report(): bool
{
if (/** Determine if the exception needs custom reporting */) {
// ...
return true;
}
return false;
}
[!NOTE] 你可以對
report方法的任何必需依賴進行類型提示,它們將自動被 Laravel 的 service container 注入到方法中。
節流回報的例外 (Throttling Reported Exceptions)
如果你的應用程式回報了非常大量的例外,你可能想要節流實際記錄或發送到應用程式外部錯誤追蹤服務的例外數量。
要對例外進行隨機抽樣,你可以在應用程式的 bootstrap/app.php 檔案中使用 throttle 例外方法。throttle 方法接收一個應該回傳 Lottery 實例的閉包:
use Illuminate\Support\Lottery;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->throttle(function (Throwable $e) {
return Lottery::odds(1, 1000);
});
})
也可以根據例外類型進行條件抽樣。如果你只想抽樣特定例外類別的實例,你可以只為該類別回傳 Lottery 實例:
use App\Exceptions\ApiMonitoringException;
use Illuminate\Support\Lottery;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->throttle(function (Throwable $e) {
if ($e instanceof ApiMonitoringException) {
return Lottery::odds(1, 1000);
}
});
})
你也可以透過回傳 Limit 實例而非 Lottery 來對記錄或發送到外部錯誤追蹤服務的例外進行速率限制。這在你想要防止突發的例外淹沒你的日誌時很有用,例如當你的應用程式使用的第三方服務故障時:
use Illuminate\Broadcasting\BroadcastException;
use Illuminate\Cache\RateLimiting\Limit;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->throttle(function (Throwable $e) {
if ($e instanceof BroadcastException) {
return Limit::perMinute(300);
}
});
})
預設情況下,限制會使用例外的類別作為速率限制鍵。你可以透過在 Limit 上使用 by 方法來指定你自己的鍵來自訂這個行為:
use Illuminate\Broadcasting\BroadcastException;
use Illuminate\Cache\RateLimiting\Limit;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->throttle(function (Throwable $e) {
if ($e instanceof BroadcastException) {
return Limit::perMinute(300)->by($e->getMessage());
}
});
})
當然,你可以為不同的例外回傳 Lottery 和 Limit 實例的混合:
use App\Exceptions\ApiMonitoringException;
use Illuminate\Broadcasting\BroadcastException;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Lottery;
use Throwable;
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->throttle(function (Throwable $e) {
return match (true) {
$e instanceof BroadcastException => Limit::perMinute(300),
$e instanceof ApiMonitoringException => Lottery::odds(1, 1000),
default => Limit::none(),
};
});
})
HTTP 例外 (Http Exceptions)
有些例外描述來自伺服器的 HTTP 錯誤碼。例如,這可能是「找不到頁面」錯誤(404)、「未授權錯誤」(401),甚至是開發者產生的 500 錯誤。為了從應用程式的任何地方產生這樣的回應,你可以使用 abort 輔助函式:
abort(404);
自訂 HTTP 錯誤頁面 (Custom Http Error Pages)
Laravel 讓你可以輕鬆地為各種 HTTP 狀態碼顯示自訂錯誤頁面。例如,要自訂 404 HTTP 狀態碼的錯誤頁面,請建立一個 resources/views/errors/404.blade.php 視圖範本。這個視圖將為你的應用程式產生的所有 404 錯誤進行渲染。此目錄中的視圖應該以它們對應的 HTTP 狀態碼命名。由 abort 函式引發的 Symfony\Component\HttpKernel\Exception\HttpException 實例會作為 $exception 變數傳遞給視圖:
<h2>{{ $exception->getMessage() }}</h2>
你可以使用 vendor:publish Artisan 命令發布 Laravel 的預設錯誤頁面範本。一旦範本被發布,你可以根據喜好自訂它們:
php artisan vendor:publish --tag=laravel-errors
備用 HTTP 錯誤頁面 (Fallback Http Error Pages)
你也可以為特定系列的 HTTP 狀態碼定義「備用」錯誤頁面。如果發生的特定 HTTP 狀態碼沒有對應的頁面,這個頁面將被渲染。為達成此目的,請在你的應用程式的 resources/views/errors 目錄中定義 4xx.blade.php 範本和 5xx.blade.php 範本。
定義備用錯誤頁面時,備用頁面不會影響 404、500 和 503 錯誤回應,因為 Laravel 對這些狀態碼有內部專用頁面。要自訂這些狀態碼渲染的頁面,你應該分別為它們定義自訂錯誤頁面。