0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js】エラー画面を表示する方法

Last updated at Posted at 2023-10-27

ページを作成する

page.tsxを以下のように作成します。

page.tsx
async function getData() {
  const res = await fetch('https://api.example.com/...')
 
  if (!res.ok) {
    throw new Error('エラーが発生しました。')
  }
 
  return res.json()
}
 
export default async function Page() {
  const data = await getData()
 
  return <main></main>
}

エラー画面を作成する

pages.tsxと同じ階層にerror.tsxを作成します。

error.tsx
'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>{error.message}</h2>
      <button onClick={() => reset()}>
        Try again
      </button>
    </div>
  )
}

上記のように記述するとpage.tsxthrow new Error('エラーが発生しました。')が実行された際にエラーが発生しました。というメッセージと再実行するためのボタンが表示されます。

error.tsxerror.messageは本番環境ではAn error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.というメッセージになります。

error.tsxと同じ階層にnot-found.tsxが存在しない場合にpage.tsxnotFound()を実行するとnot-found.tsxが表示されるのではなく、error.tsxerror.messageNEXT_NOT_FOUNDが渡されて表示されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?