
try ~ catch ~ finally 구문을 활용한다.try {
// 로직
} catch(err) {
// 에러 발생 시 로직
} finally {
// 무조건 실행되는 코드
}
error 객체는 일반적으로 Error 클래스의 인스턴스이다.
message를 포함해 몇 가지 자주 사용되는 속성은 다음과 같다.
const customError = new Error("Custom error message");
console.log(customError.name); // 출력: "Error"
try {
throw new Error("Custom error message");
} catch (error) {
console.log(error.stack);
}
try {
throw new Error("This is an error message");
} catch (error) {
console.log(error.message); // 출력: "This is an error message"
}
const customError = new Error("Custom error message");
console.log(customError.toString()); // 출력: "Error: Custom error message"
console.log(error)만 출력할 경우, 브라우저 콘솔 또는 Node.js 콘솔에 따라 형식이 다를 수 있지만, 에러 객체 전체를 출력하여, 에러 이름, 메서지, 또는 스택 트레이스 정보까지도 출력 가능하다.
예시)Error: Custom error message at <anonymous>:x:y
function getSize(length) {
if (typeof length !== 'number') {
throw new Error('Parameter is not a number!');
}
return length;
}
try {
getSize('a');
} catch (e) {
console.error(e);
}
instanceof 사용하기try {
// ...
} catch (error) {
if (error instanceof TypeError) {
console.error("Caught a TypeError: " + error.message);
} else if (error instanceof ReferenceError) {
console.error("Caught a ReferenceError: " + error.message);
} else if (error instanceof SyntaxError) {
console.error("Caught a SyntaxError: " + error.message);
} else if (error instanceof RangeError) {
console.error("Caught a RangeError: " + error.message);
} else {
console.error("Caught an unexpected error: " + error);
}
}
error.name 사용하기try {
// ...
} catch (error) {
if (error.name === "ReferenceError") {
// 참조 에러일 경우의 처리
} else if (error.name === "SyntaxError") {
// 구문 에러일 경우의 처리
} else if (error.name === "TypeError") {
// 타입 에러일 경우의 처리
} else {
// 그 외의 에러일 경우의 처리
}
}
Error 클래스를 상속받는 형식으로 구현 가능하다.
// 사용자 정의 예외 타입
class MyError extends Error { // Error 부모 클래스를 상속한다.
constructor(message) {
super(message); //MyError의 this가 Error의 객체 this 호출 -> Error의 생성자를 작동시킴
this.name = 'MyError';
}
}
try {
throw new MyError('Something went wrong');
} catch (error) {
// 에러 객체를 받아서 처리
if (error.name === "MyError") {
console.log(error.message); // 'Something went wrong'
}
}
settimeout, promise의 예외 처리 더 공부하기/ 참고: https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-%EC%98%88%EC%99%B8-%EC%B2%98%EB%A6%AC