강의

멘토링

커뮤니티

Inflearn Community Q&A

hwuiinn's profile image
hwuiinn

asked

Next + Create a SNS service with React Query

Handling Error Situations (No User Information)

프로필 부분 getUser.ts Error가 반환되지 않는 이유를 모르겠습니다.

Written on

·

185

·

Edited

0

import { QueryFunction } from "@tanstack/react-query";
import { User } from "@/model/User";

const getUser: QueryFunction<User, [string, string]> = async ({ queryKey }) => {
  const [_1, username] = queryKey;

  const res = await fetch(`http://localhost:9090/api/users/${username}`, {
    next: {
      tags: ["users", username],
    },
    cache: "no-store",
  });

  console.log("res.ok : ", res.ok);

  if (!res.ok) {
    throw new Error("해당 유저 정보를 불러오지 못 했습니다.");
  }

  return res.json();
};

export default getUser;

mocks>handler.ts에 없는 username을 url에 입력해도 res.ok로 떠서 if문을 그냥 통과해버립니다.

혹시 제가 놓치는 부분이 있는걸까요?

reactnext.jsreact-querynext-authmsw

Answer 1

1

zerocho님의 프로필 이미지
zerocho
Instructor

handler.ts 코드를 봐야겠는데요? handler.ts에도 없는 경우 에러를 응답하고 있어야 합니다.

hwuiinn님의 프로필 이미지
hwuiinn
Questioner

아.. 해결했습니다. 제가 이전에 반환을 아래 코드로 진행했었습니다.

이렇게 return하고 있었어서 못 알아챘던 것 같습니다.

http.get("api/users/:userId", ({ request, params }) => {
    const { userId } = params;
    const found = User.find((v) => v.id === userId);

    if (found) {
      return HttpResponse.json(found);
    } else {
      return HttpResponse.json({
        message: "유저를 찾지 못했습니다.",
        errorStatus: 404,
      });
    }
  }),
http.get("api/users/:userId", ({ request, params }) => {
    const { userId } = params;
    const found = User.find((v) => v.id === userId);

    if (found) {
      return HttpResponse.json(found);
    } else {
      return HttpResponse.json(
        {
          message: "유저를 찾지 못했습니다.",
        },
        {
          status: 404,
        }
      );
    }
  }),

아래 코드로 수정하니 해결되었습니다. 이전 코드는 왜 에러 캐칭이 되지 않았는지 알아보겠습니다. ㅠ

칼답변 감사드립니다.


--- + 1번 코드와 2번 코드 차이? 
A. HttpResponse.json()의 첫 번째 인자는 무조건 200을 반환한다. 따라서 에러 코드를 반환하기 위해서는 명시적으로 두 번째 인자에 에러 상태코드를 작성해주자.

hwuiinn's profile image
hwuiinn

asked

Ask a question