使用穩健的伺服器端框架的優點之一是,您可以免費獲得內建的例外處理。例如,Laravel 附帶了 Ignition,這是一個美觀的錯誤報告工具,可在本地開發中顯示格式精美的堆疊追蹤。
挑戰在於,如果您發出 XHR 請求(Inertia 會這樣做)並且遇到伺服器端錯誤,您通常會需要在瀏覽器的開發人員工具中的網路標籤中挖掘才能診斷問題。
Inertia 通過在模態視窗中顯示所有非 Inertia 的回應來解決此問題。這意味著您可以獲得您習慣的相同美觀的錯誤報告,即使您是通過 XHR 發出請求也是如此。
在生產環境中,您會希望返回正確的 Inertia 錯誤回應,而不是依賴開發期間存在的模態驅動錯誤報告。為此,您需要更新框架的預設例外處理程式以返回自訂錯誤頁面。
在建立 Laravel 應用程式時,您可以使用應用程式的 bootstrap/app.php
檔案中的 respond
例外方法來完成此操作。
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Inertia\Inertia;
->withExceptions(function (Exceptions $exceptions) {
$exceptions->respond(function (Response $response, Throwable $exception, Request $request) {
if (! app()->environment(['local', 'testing']) && in_array($response->getStatusCode(), [500, 503, 404, 403])) {
return Inertia::render('Error', ['status' => $response->getStatusCode()])
->toResponse($request)
->setStatusCode($response->getStatusCode());
} elseif ($response->getStatusCode() === 419) {
return back()->with([
'message' => 'The page expired, please try again.',
]);
}
return $response;
});
})
您可能已經注意到,在上面的範例中,我們返回了一個 Error
頁面元件。您需要實際建立此元件,它將作為應用程式的通用錯誤頁面。以下是一個您可以使用的錯誤元件範例作為起點。
<script setup>
import { computed } from 'vue'
const props = defineProps({ status: Number })
const title = computed(() => {
return {
503: '503: Service Unavailable',
500: '500: Server Error',
404: '404: Page Not Found',
403: '403: Forbidden',
}[props.status]
})
const description = computed(() => {
return {
503: 'Sorry, we are doing some maintenance. Please check back soon.',
500: 'Whoops, something went wrong on our servers.',
404: 'Sorry, the page you are looking for could not be found.',
403: 'Sorry, you are forbidden from accessing this page.',
}[props.status]
})
</script>
<template>
<div>
<H1>{{ title }}</H1>
<div>{{ description }}</div>
</div>
</template>