エラーハンドリング
このドキュメントでは、開発環境、サーバーサイド、クライアントサイドのエラーをどのように処理できるかを説明します。
開発環境でのエラー処理
Next.jsアプリケーションの開発フェーズ中にランタイムエラーが発生すると、オーバーレイが表示されます。これはウェブページを覆うモーダルです。pnpm dev
、npm run dev
、yarn dev
、またはbun dev
を介してnext dev
を使用して開発サーバーが実行されている場合にのみ表示され、本番環境では表示されません。エラーを修正すると、オーバーレイは自動的に消えます。
オーバーレイの例はこちら
サーバーエラーの処理
Next.jsは、アプリケーションで発生するサーバーサイドエラーを処理するために、デフォルトで静的な500ページを提供します。pages/500.js
ファイルを作成することで、このページをカスタマイズすることもできます。
アプリケーションに500ページがあっても、アプリユーザーに特定のエラーは表示されません。
また、404ページを使用して、file not found
などの特定のランタイムエラーを処理することもできます。
クライアントエラーの処理
Reactのエラーバウンダリは、アプリケーションの他の部分が動作し続けるように、クライアント上のJavaScriptエラーを適切に処理する方法です。ページのクラッシュを防ぐだけでなく、カスタムのフォールバックコンポーネントを提供し、エラー情報をログに記録することもできます。
Next.jsアプリケーションでエラーバウンダリを使用するには、ErrorBoundary
というクラスコンポーネントを作成し、pages/_app.js
ファイルでComponent
プロップをラップする必要があります。このコンポーネントは以下の責任を負います。
- エラーがスローされた後にフォールバック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
コンポーネントを作成したら、Next.jsアプリケーションでComponent
プロップをラップするためにpages/_app.js
ファイルにインポートします。
// 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などのサービスを使用します。
お役に立ちましたか?