2차 공부/TIL

24.10.07 nextjs 에러핸들링

공대탈출 2024. 10. 8. 21:26
{
    "todoList": [
        {
            "id": "adsf",
            "title": "titleTest",
            "desc": "DescTest",
            "isCompleted": false,
            "createdAt": 123
        },
        {
            "id": "adsd",
            "title": "titleTest",
            "desc": "DescTest",
            "isCompleted": false,
            "createdAt": 123
        }
    ]
}

json-server를 이용하여 간단한 투두리스트를 만들었다.

내가 개인과제를 진행하며 제일 궁금했던건 CSR페이지에서 route.ts로 fetch를 했을 때 에러핸들링을 어떻게 할 것이냐는 것이다.

import { Todo } from "@/types/Todo";
import { NextResponse } from "next/server";

export const BASEURL = "http://localhost:4000";

export async function GET() {
    try {
        const res = await fetch(`${BASEURL}/todoList`, { cache: "no-store" });
        const data: Todo[] = await res.json();
        return NextResponse.json({ data });
    } catch (error) {
        console.log("error :>> ", error);
        throw { message: "에러발생" };
    }
}

route handler는 이렇게 생겼다.

try catch를 사용하여 에러를 잡아내 에러를 던져준다.

"use client";

import { Todo } from "@/types/Todo";
import { useEffect, useState } from "react";

const BASEURL = "http://localhost:3000";
const HomePage = () => {
    const [todos, setTodos] = useState<Todo[]>();
    const [isError, setIsError] = useState(false);
    const fetchTodos = async () => {
        try {
            const todoRes = await fetch(`${BASEURL}/api/todos`);
            console.log("todoRes :>> ", todoRes);
            const { data: todoData }: { data: Todo[] } = await todoRes.json();
            setTodos(todoData);
        } catch {
            console.log("1 :>> ", 1);
            setIsError(true);
        }
    };
    useEffect(() => {
        fetchTodos();
    }, []);
    if (isError) throw new Error("1`");
    return (
        <div className="flex flex-col justify-center items-center py-[200px]">
            <h1>투두리스트</h1>
            <ul>
            	//...
            </ul>
        </div>
    );
};

export default HomePage;

맨 처음에는 try catch를 여기서도 사용하여 throw new Error를 통해 에러페이지로 이동하게끔 했는데, useEffect 안에서 throw되어서 그런지 에러를 잡아내지 못했다.

그래서 에러상태를 state로 만들어주고, catch구문으로 들어갈 시 setIsError를 true로 만들어 에러페이지를 화면에 보여주게끔 설정하였다.

'2차 공부 > TIL' 카테고리의 다른 글

24.10.10  (1) 2024.10.11
24.10.08 개인프로젝트 마무리  (2) 2024.10.08
24.10.02 개인프로젝트 트러블슈팅  (0) 2024.10.02
24.10.01 트러블 슈팅  (1) 2024.10.02
24.09.30 트러블 슈팅  (0) 2024.10.02