
Error: 기본 에러 객체. 모든 에러의 부모.SyntaxError: 문법 오류.ReferenceError: 존재하지 않는 변수를 참조할 때 발생.TypeError: 변수나 값의 타입이 유효하지 않을 때 발생.RangeError: 숫자 범위가 허용되지 않을 때 발생.URIError: decodeURI 또는 encodeURI 함수 사용 시 잘못된 URI가 제공될 때 발생.try-catch는 에러를 감지하고 처리할 수 있는 기본 구조
try {
// 에러가 발생할 수 있는 코드
throw new Error("Something went wrong");
} catch (error) {
// 에러 처리
console.error("Caught an error:", error.message);
} finally {
// 항상 실행되는 블록 (선택적)
console.log("This runs no matter what.");
}
try {
throw new TypeError("Invalid type provided");
} catch (error) {
console.log(error.name); // TypeError
console.log(error.message); // Invalid type provided
}
Promise에서 에러는 reject를 호출하거나 함수 내부에서 throw로 발생시킬 수 있음.
const asyncOperation = () =>
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("Async error occurred"));
}, 1000);
});
asyncOperation()
.then((result) => console.log(result))
.catch((error) => console.error("Caught error:", error.message));
async/await를 사용하면 비동기 코드도 동기 코드처럼 try-catch로 에러를 처리할 수 있음.
const fetchData = async () => {
try {
const response = await fetch("invalid-url");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error during fetch:", error.message);
}
};
fetchData();
Error 클래스를 상속받아 특정 목적에 맞는 에러를 정의할 수 있음.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Invalid data format");
} catch (error) {
console.error(`${error.name}: ${error.message}`); // ValidationError: Invalid data format
}
