node.jserror-handlingnode
Node.js 에러 처리 - 비동기 에러 핸들링 패턴
조회 0
Node.js에서 비동기 에러를 올바르게 처리하는 것은 안정적인 애플리케이션을 만드는 핵심입니다.
이 글에서는 콜백, Promise, async/await에서의 에러 처리 패턴을 정리합니다.
1. 콜백 에러 처리
const fs = require("fs");
fs.readFile("file.txt", "utf8", (err, data) => {
if (err) {
console.error("에러:", err);
return;
}
console.log(data);
});
- 콜백의 첫 번째 인자는 항상 에러 객체입니다.
2. Promise 에러 처리
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => {
console.error("에러:", error);
});
3. async/await 에러 처리
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = response.();
.(data);
} (error) {
.(, error);
}
}