본문 바로가기
개발정리 (nodeJS)

[nodeJS] 에러 및 예외 처리 방법

by 할리갈리0 2023. 8. 6.

1. Try-Catch 구문

try 블록에서 예외가 발생하면 즉시 catch 블록으로 이동하여 예외를 처리

function syncFunction() {
  // 예외 발생 가능한 코드
  throw new Error("Error occurred");
}

try {
  syncFunction();
} catch (error) {
  console.error("Catch block handling the error:", error);
}

 

2. Error-first Callback (오류 우선 콜백)

Node.js에서 콜백 함수의 첫 번째 매개변수는 오류고 나머지 매개변수는 결과 데이터

const fs = require("fs");

fs.readFile("non_file.txt", "utf8", (error, data) => {
  if (error) {
    console.error("Error handling in callback:", error);
    return;
  }
  console.log("File content:", data);
});

 

3. Promise 

프로미스는 then, catch, finally 메소드를 사용하여 성공하는 경우, 실패하는 경우로 구성 가능

function myFunction() {
  return new Promise((resolve, reject) => {
    if (/* error condition */) {
      reject(new Error("Error occurred"));
    } else {
      resolve("Success");
    }
  });
}

myFunction()
  .then((result) => {
    console.log("Success:", result);
  })
  .catch((error) => {
    console.error("Error handling with Promise:", error);
  });

 

프로젝트를 개발하면서 가장 적합하거나 쉬운 방법을 사용하여 코드의 안정성과 에러 대응력을 높일 수 있습니다.

반응형