에러처리

2025. 6. 12. 13:14Coding Study/네트워크

 

 

 

export async function fetchPlaces() {
  const res = await fetch(`http://localhost:3000/places`);
  console.log(res);

  if (!res.ok) {
    throw new Error("에러가 발생했습니다.");
  }

  const data = await res.json();
  return data.places;
}

 

 

패치 후 res 값을 확인 시

 

<성공 시>

Response {
  status: 200,
  statusText: 'OK',
  headers: Headers {
    'x-powered-by': 'Express',
    'access-control-allow-origin': '*',
    'access-control-allow-methods': 'GET, PUT, POST, DELETE',
    'access-control-allow-headers': 'Content-Type',
    'content-type': 'application/json; charset=utf-8',
    'content-length': '2545',
    etag: 'W/"9f1-y5KETN1Rw+rXp06PeNuvZTlsukI"',
    date: 'Thu, 12 Jun 2025 01:27:15 GMT',
    connection: 'keep-alive',
    'keep-alive': 'timeout=5'
  },
  body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true },
  bodyUsed: false,
  ok: true,
  redirected: false,
  type: 'default',
  url: 'http://localhost:3000/places'
}

 

<실패 시>

Response {
  status: 404,
  statusText: 'Not Found',
  headers: Headers {
    'x-powered-by': 'Express',
    'access-control-allow-origin': '*',
    'access-control-allow-methods': 'GET, PUT, POST, DELETE',
    'access-control-allow-headers': 'Content-Type',
    'content-type': 'application/json; charset=utf-8',
    'content-length': '29',
    etag: 'W/"1d-F04Dovy4J3bNS0U4v0hMsdAitGg"',
    date: 'Thu, 12 Jun 2025 01:29:45 GMT',
    connection: 'keep-alive',
    'keep-alive': 'timeout=5'
  },
  body: ReadableStream { locked: false, state: 'readable', supportsBYOB: true },
  bodyUsed: false,
  ok: false,
  redirected: false,
  type: 'default',
  url: 'http://localhost:3000/place'
}

 

 

상태코드 명칭 설명

200 OK 요청이 성공적으로 처리되었을 때 사용됨 (일반적인 성공 응답).
201 Created 요청이 성공적으로 처리되었고, 새로운 리소스가 생성되었을 때 사용됨 (POST 요청에 주로 사용).
204 No Content 요청이 성공했으나, 응답할 콘텐츠가 없을 때 사용됨. 일반적으로 삭제 요청(DELETE) 후 반환됨.
400 Bad Request 클라이언트의 요청이 잘못되었을 때 사용됨 (형식 오류, 필수 값 누락 등).
401 Unauthorized 인증이 필요한 요청에서 인증 정보가 없거나 올바르지 않을 때 사용됨.
403 Forbidden 요청이 서버에 의해 거부되었을 때 사용됨 (인증은 되었지만 권한 없음).
404 Not Found 요청한 리소스를 찾을 수 없을 때 사용됨 (잘못된 URL 등).
500 Internal Server Error 서버 내부 오류로 인해 요청을 처리할 수 없을 때 사용됨.

 

 

상태코드 클라이언트 처리 전략

200 - 정상 응답 처리
- 데이터를 받아와서 렌더링 또는 UI 업데이트
201 - 성공 메시지 표시 (예: "등록되었습니다.")
- 새로 생성된 리소스를 화면에 반영
204 - 성공 메시지 없이 UI 변경 (예: 목록에서 아이템 제거)
- 필요 시 사용자에게 "삭제 완료" 알림
400 - 입력값 검증 후 클라이언트에서 오류 메시지 제공
- 어떤 입력이 잘못되었는지 사용자에게 명확히 안내
401 - 로그인 페이지로 리다이렉트 또는 로그인 모달 표시-
인증 만료 시 토큰 제거 후 재로그인 유도
403 - 접근 권한 없음 안내- "접근 권한이 없습니다" 등의 메시지 표시- 관리자에게 문의 유도
404 - 사용자에게 "페이지를 찾을 수 없습니다" 또는 "데이터가 없습니다" 메시지 표시- 홈이나 이전 페이지로 유도
500 - "서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요" 등의 일반 오류 메시지 표시
- 사용자에게 내부 로직은 노출하지 않음- 서버 응답 로그 기록 및 모니터링 필요

 

 

export async function fetchPlaces() {
  const res = await fetch(`http://localhost:3000/places`);

  if (!res.ok) {
    switch (res.status) {
      case 400:
        throw new Error("잘못된 요청입니다. 입력값을 확인해주세요.");
      case 401:
        throw new Error("로그인이 필요합니다.");
      case 403:
        throw new Error("접근 권한이 없습니다.");
      case 404:
        throw new Error("요청한 장소 정보를 찾을 수 없습니다.");
      case 500:
        throw new Error("서버 오류가 발생했습니다. 잠시 후 다시 시도해주세요.");
      default:
        throw new Error("알 수 없는 오류가 발생했습니다.");
    }
  }

  const data = await res.json();
  return data.places;
}

 

'Coding Study > 네트워크' 카테고리의 다른 글

SOP 와 CORS  (2) 2025.05.12
HTTPS  (0) 2025.05.12
HTTP  (0) 2025.05.12
네트워크란  (0) 2025.05.12