2
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?

【Next.js】エラー伝播の流れ図解で理解

Posted at

はじめに

 Next.jsで開発中に、このエラーはどこに向かって投げられているのか?という疑問から頭の整理をするため図にしてみました。


下記のように書いていました

.blogs/page.tsx

async function Page() {
  const fetchAllBlogsData = async (): Promise<BlogResponse> => {
    const res = await fetch(`https://hoge.microcms.io/api/v1/blogs`, {
      next: { revalidate: 600 },
      headers: {
        "X-MICROCMS-API-KEY": process.env.CMS_API_KEY || "",
        "Content-Type": "application/json",
      },
    });
    if (!res.ok) throw new Error("データ取得に失敗しました");
    return await res.json();
  };
  const allBlogs = await fetchAllBlogsData();

  return (
    <div>
      <Header />
      <PageClient allBlogs={allBlogs} />
      </div>
  );
}

export default Page;

.blogs/page.client.tsx
"use client";

const limit = 8;

function PageClient({ allBlogs }: { allBlogs: BlogResponse }) {
  const [currentPage, setCurrentPage] = useState(1);
  const totalPages = Math.ceil(allBlogs.contents.length / limit);
  return (
    <>
      <div className="flex items-center justify-between mt-4 mb-4 ml-10">
        <div className="cms-heading text-xl font-bold">ブログ記事一覧</div>
        <div>
          <Link
            href="/"
            className="btn mr-10 c-btn-slide4 px-6 py-2 font-bold text-[#fff] bg-[#5696e3] border border-[#5696e3] rounded">
            戻る
          </Link>
        </div>
      </div>

      <div className="grid justify-items-center md:grid-cols-2 gap-4 lg:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4 2xl:grid-row-2">
        {allBlogs.contents.map((blogs) => {
          return (
            <Link
              href={`/blogs/${blogs.id}`}
              key={blogs.id}
              className="image-animation card bg-base-100 w-96 shadow-lg">
              <figure>
                <Image src={CmsThumbnail} alt="画像" width={400} height={300} priority={true} />
              </figure>
              <div className="card-body bg-base-content/5">
                <p>{formattedDate(blogs.createdAt)}</p>
                <h2 className="card-title">{blogs.title}</h2>
              </div>
            </Link>
          );
        })}
      </div>

      <div className="grid grid-cols-3 items-center mt-4">
        <div></div>
        <div className="justify-self-center">
          <CmsClientSidePagenation currentPage={currentPage} totalPages={totalPages} onPageChange={setCurrentPage} />
        </div>
      </div>
    </>
  );
}

export default PageClient;

上記のコードの流れ

通常の流れ.png

エラーが発生した場合

try-catchしない流れ.png

しかしこれだとエラーが発生した場合に任意の処理ができないため、一旦エラーをキャッチしたいという考え方もあるようです。
try-catchを使用するとエラーは一旦catchで捕まります。しかしキャッチしたままだとエラーがバウンダリーに投げられずerror.tsxの表示に影響する可能性があるため再throwしています。

.blogs/page.tsx
try {
      const res = await fetch(`https://hoge.microcms.io/api/v1/blogs`, {
        next: { revalidate: 600 },
        headers: {
          "X-MICROCMS-API-KEY": process.env.CMS_API_KEY || "",
          "Content-Type": "application/json",
        },
      });
      if (!res.ok) throw new Error("データ取得に失敗しました");
      return await res.json();
    } catch (error) {
      console.error("データ取得エラー", error);
      throw error;
    }

try-catchする流れ.png

参考

おわりに

文字だけの理解よりも図にするのが良いと改めて思いました。 


JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

2
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
2
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?