エラーハンドリング方法
エラーは予期されるエラーとキャッチされない例外の2つのカテゴリに分けられます。このページでは、Next.jsアプリケーションでこれらのエラーを処理する方法を説明します。
予期されるエラーの処理
予期されるエラーとは、サーバーサイドフォームバリデーションや失敗したリクエストなど、アプリケーションの通常の操作中に発生する可能性のあるエラーです。これらのエラーは明示的に処理され、クライアントに返されるべきです。
サーバー関数
サーバー関数内で予期されるエラーを処理するには、useActionState
フックを使用できます。
これらのエラーに対しては、try
/catch
ブロックを使用したりエラーをスローしたりするのではなく、予期されるエラーを戻り値としてモデル化します。
'use server'
export async function createPost(prevState: any, formData: FormData) {
const title = formData.get('title')
const content = formData.get('content')
const res = await fetch('https://api.vercel.app/posts', {
method: 'POST',
body: { title, content },
})
const json = await res.json()
if (!res.ok) {
return { message: 'Failed to create post' }
}
}
'use server'
export async function createPost(prevState, formData) {
const title = formData.get('title')
const content = formData.get('content')
const res = await fetch('https://api.vercel.app/posts', {
method: 'POST',
body: { title, content },
})
const json = await res.json()
if (!res.ok) {
return { message: 'Failed to create post' }
}
}
アクションをuseActionState
フックに渡し、返されたstate
を使用してエラーメッセージを表示できます。
'use client'
import { useActionState } from 'react'
import { createPost } from '@/app/actions'
const initialState = {
message: '',
}
export function Form() {
const [state, formAction, pending] = useActionState(createPost, initialState)
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input type="text" id="title" name="title" required />
<label htmlFor="content">Content</label>
<textarea id="content" name="content" required />
{state?.message && <p aria-live="polite">{state.message}</p>}
<button disabled={pending}>Create Post</button>
</form>
)
}
'use client'
import { useActionState } from 'react'
import { createPost } from '@/app/actions'
const initialState = {
message: '',
}
export function Form() {
const [state, formAction, pending] = useActionState(createPost, initialState)
return (
<form action={formAction}>
<label htmlFor="title">Title</label>
<input type="text" id="title" name="title" required />
<label htmlFor="content">Content</label>
<textarea id="content" name="content" required />
{state?.message && <p aria-live="polite">{state.message}</p>}
<button disabled={pending}>Create Post</button>
</form>
)
}
サーバーコンポーネント
サーバーコンポーネント内でデータを取得する場合、レスポンスを使用してエラーメッセージを条件付きでレンダリングしたり、redirect
したりできます。
export default async function Page() {
const res = await fetch(`https://...`)
const data = await res.json()
if (!res.ok) {
return 'There was an error.'
}
return '...'
}
export default async function Page() {
const res = await fetch(`https://...`)
const data = await res.json()
if (!res.ok) {
return 'There was an error.'
}
return '...'
}
Not found(見つからない場合)
ルートセグメント内でnotFound
関数を呼び出し、not-found.js
ファイルを使用して404 UIを表示できます。
import { getPostBySlug } from '@/lib/posts'
export default async function Page({ params }: { params: { slug: string } }) {
const { slug } = await params
const post = getPostBySlug(slug)
if (!post) {
notFound()
}
return <div>{post.title}</div>
}
import { getPostBySlug } from '@/lib/posts'
export default async function Page({ params }) {
const { slug } = await params
const post = getPostBySlug(slug)
if (!post) {
notFound()
}
return <div>{post.title}</div>
}
export default function NotFound() {
return <div>404 - Page Not Found</div>
}
export default function NotFound() {
return <div>404 - Page Not Found</div>
}
キャッチされない例外の処理
キャッチされない例外は、アプリケーションの通常のフロー中に発生すべきではないバグや問題を示す予期しないエラーです。これらのエラーはスローされ、エラーバウンダリによってキャッチされるべきです。
ネストされたエラーバウンダリ
Next.jsはキャッチされない例外を処理するためにエラーバウンダリを使用します。エラーバウンダリは子コンポーネント内のエラーをキャッチし、クラッシュしたコンポーネントツリーの代わりにフォールバックUIを表示します。
ルートセグメント内にerror.js
ファイルを追加し、Reactコンポーネントをエクスポートすることでエラーバウンダリを作成します:
'use client' // エラーバウンダリはクライアントコンポーネントである必要があります
import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
// エラーをエラー報告サービスに記録
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// セグメントを再レンダリングして復旧を試みる
() => reset()
}
>
Try again
</button>
</div>
)
}
'use client' // エラーバウンダリはクライアントコンポーネントである必要があります
import { useEffect } from 'react'
export default function Error({ error, reset }) {
useEffect(() => {
// エラーをエラー報告サービスに記録
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button
onClick={
// セグメントを再レンダリングして復旧を試みる
() => reset()
}
>
Try again
</button>
</div>
)
}
エラーは最も近い親のエラーバウンダリまでバブルアップします。これにより、ルート階層の異なるレベルにerror.tsx
ファイルを配置することで、細かいエラーハンドリングが可能になります。

グローバルエラー
あまり一般的ではありませんが、ルートレイアウトでエラーを処理するには、国際化を活用している場合でも、ルートappディレクトリにあるglobal-error.js
ファイルを使用できます。グローバルエラーUIは、アクティブ時にルートレイアウトやテンプレートを置き換えるため、独自の<html>
タグと<body>
タグを定義する必要があります。
'use client' // エラーバウンダリはクライアントコンポーネントである必要があります
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
// global-errorにはhtmlタグとbodyタグを含める必要があります
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
'use client' // エラーバウンダリはクライアントコンポーネントである必要があります
export default function GlobalError({ error, reset }) {
return (
// global-errorにはhtmlタグとbodyタグを含める必要があります
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}