錯誤處理
本文件說明如何處理開發、伺服器端和用戶端錯誤。
開發期間的錯誤處理
當您的 Next.js 應用程式在開發階段發生運行階段錯誤時,您會遇到一個覆蓋層。這是一個覆蓋網頁的模態視窗。它僅在開發伺服器使用 next dev
透過 pnpm dev
、npm run dev
、yarn dev
或 bun dev
執行時可見,且不會在生產環境中顯示。修正錯誤將自動關閉覆蓋層。
以下是一個覆蓋層的範例
伺服器錯誤處理
Next.js 預設提供靜態 500 頁面來處理應用程式中發生的伺服器端錯誤。您也可以透過建立 pages/500.js
檔案來自訂此頁面。
在您的應用程式中使用 500 頁面不會向應用程式使用者顯示特定錯誤。
您也可以使用 404 頁面來處理特定的運行階段錯誤,例如 找不到檔案
。
用戶端錯誤處理
React 錯誤邊界 是一種優雅的方式來處理用戶端 JavaScript 錯誤,讓應用程式的其他部分可以繼續運作。除了防止頁面崩潰之外,它還允許您提供自訂的回退組件,甚至記錄錯誤資訊。
若要為您的 Next.js 應用程式使用錯誤邊界,您必須建立一個類別組件 ErrorBoundary
,並將 pages/_app.js
檔案中的 Component
prop 包裹起來。此組件將負責:
- 在拋出錯誤後渲染回退 UI
- 提供重設應用程式狀態的方法
- 記錄錯誤資訊
您可以透過擴展 React.Component
來建立 ErrorBoundary
類別組件。例如:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
// Define a state variable to track whether is an error or not
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI
return { hasError: true }
}
componentDidCatch(error, errorInfo) {
// You can use your own error logging service here
console.log({ error, errorInfo })
}
render() {
// Check if the error is thrown
if (this.state.hasError) {
// You can render any custom fallback UI
return (
<div>
<h2>Oops, there is an error!</h2>
<button
type="button"
onClick={() => this.setState({ hasError: false })}
>
Try again?
</button>
</div>
)
}
// Return children components in case of no error
return this.props.children
}
}
export default ErrorBoundary
ErrorBoundary
組件追蹤 hasError
狀態。此狀態變數的值為布林值。當 hasError
的值為 true
時,ErrorBoundary
組件將渲染回退 UI。否則,它將渲染子組件。
建立 ErrorBoundary
組件後,將其匯入 pages/_app.js
檔案,以將 Next.js 應用程式中的 Component
prop 包裹起來。
// Import the ErrorBoundary component
import ErrorBoundary from '../components/ErrorBoundary'
function MyApp({ Component, pageProps }) {
return (
// Wrap the Component prop with ErrorBoundary component
<ErrorBoundary>
<Component {...pageProps} />
</ErrorBoundary>
)
}
export default MyApp
您可以在 React 的文件中了解更多關於 錯誤邊界 的資訊。
錯誤回報
若要監控用戶端錯誤,請使用像 Sentry、Bugsnag 或 Datadog 之類的服務。
這有幫助嗎?