[JavaScript] fetch, try, catch란?
JavaScript에서 비동기적으로 데이터를 가져오거나 오류를 처리할 때 자주 사용되는 기능들.
1️⃣ fetch
fetch는 웹에서 데이터를 가져오는 함수.
브라우저의 네트워크 요청(HTTP 요청) 을 처리하는 기본적인 API.
📌 기본 사용법
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json()) // JSON 형식으로 변환
.then(data => console.log(data)) // 변환된 데이터 출력
.catch(error => console.error("에러 발생:", error)); // 오류 처리
📌 fetch는 Promise 기반
• .then(response => response.json()) → 서버 응답을 JSON으로 변환
• .then(data => console.log(data)) → 변환된 데이터를 출력
• .catch(error => console.error(error)) → 요청 중 에러가 발생하면 처리
📌 async/await으로 fetch 사용하기
더 깔끔한 코드 작성을 위해 async/await 사용.
async function getData() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
}
getData();
await fetch(...)를 사용하면 Promise를 .then() 없이 동기 코드처럼 사용할 수 있다.
2️⃣ try...catch
JavaScript에서 오류(예외)를 처리할 때 사용하는 구문.
try 안에서 오류가 발생하면, catch가 실행돼서 오류를 잡을 수 있다.
📌 기본 사용법
try {
let result = riskyFunction(); // 오류 발생 가능성 있는 코드
console.log(result);
} catch (error) {
console.error("오류 발생!", error);
}
오류가 발생해도 프로그램이 멈추지 않고 처리 가능함
📌 fetch + try...catch로 오류 처리하기
인터넷 연결이 끊겼거나, API 요청이 잘못되었을 때 오류를 처리하는 방법.
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/invalid-url");
if (!response.ok) throw new Error("네트워크 응답이 올바르지 않습니다!");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("데이터 가져오기 실패:", error);
}
}
fetchData();
📌 fetch 요청이 실패할 수 있는 경우
1️⃣ 잘못된 URL 요청 (404 Not Found)
2️⃣ 서버 오류 발생 (500 Internal Server Error)
3️⃣ 인터넷 연결 문제
try...catch를 사용하면 이러한 오류를 방지하고 프로그램을 안전하게 실행할 수 있다.
🎯 정리
fetch → 웹에서 데이터를 가져오는 비동기 함수
try...catch → 코드 실행 중 발생하는 오류를 잡아주는 기능
fetch와 try...catch를 함께 사용하면 네트워크 오류를 안전하게 처리 가능