Unexpected end of JSON input

서동이·2024년 8월 8일

1. Problems

1. 받아온 response가 제대로 된 JSON 형태로 보내주는 것이 아니어서 에러가 발생

2. route api에서 기본 에러처리만 하고 받은 에러값을 적용하고 있지 않음.

2. Solution

1번 문제 해결방안

  • JsonResponse 가 아닌 HttpResponse 를 보내주는 경우에 대한 에러핸들링을 하였다.
const useMarkers = (currAddress?: string) => {
  const gu: SeoulGuType | null = currAddress ? searchGu(currAddress) : 'Seocho';

  const fetchMarkers = useCallback(async (gu: SeoulGuType) => {
    try {
      const res = await fetch(`/api/area/gu?type=${encodeURIComponent(gu)}`);

 
     //  <----- 응답 상태 코드 확인 코드 추가
     
      if (!res.ok) {
        switch (res.status) {
          case 400:
            alert(`해당 지역(${gu})의 URL이 설정되어 있지 않습니다.`);
            throw new Error(`HTTP error! status: ${res.status}`);
          case 403:
            alert('API 키가 설정되지 않았습니다. 환경 변수를 확인하세요.');
            throw new Error(`HTTP error! status: ${res.status}`);
          case 404:
            alert('해당지역은 관련정보를 제공하고 있지 않습니다. 해당 구청에 문의 바랍니다.');
            throw new Error(`HTTP error! status: ${res.status}`);
          default:
            throw new Error(`HTTP error! status: ${res.status}`);
        }
      }
 	//  ----->

      const result: { data: AddressDto[] } = await res.json();

      const markers = result.data.map((a) => new MarkerData(a));
      return markers;
    } catch (err: any) {
      console.error('Fetch error:', err);
      return [];
    }
  }, []);

2번 문제 해결방안

// app>api>route.ts

// https://stackoverflow.com/questions/76214029/no-http-methods-exported-in-export-a-named-export-for-each-http-method
export async function GET(req: NextRequest) {
  const url = new URL(req.url);
  const gu: SeoulGuType = (url.searchParams.get('type') as SeoulGuType) || 'Seocho';

  try {
    const data = await fetchArea(gu, 50);

    return NextResponse.json({ data });
  } catch (err: any) {
    
    // 기존코드
    // return NextResponse.error()
     
    // <---- 수정코드
    if (err instanceof ApiError) {
      // ApiError를 처리하여 클라이언트에 적절한 메시지와 상태 코드 반환
      return NextResponse.json({ error: err.message }, { status: err.statusCode });
    }
    // 일반적인 오류 처리
    console.error('Server error:', err);
    return NextResponse.json({ error: '서버 오류가 발생했습니다.' }, { status: 500 });
  }
   // --------->
}

참고자료
https://jindev-t.tistory.com/91

profile
블로그 이전했어요> https://seod0209.github.io

0개의 댓글