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번 문제 해결방안
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) {
if (err instanceof 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