에러 객체


자바스크립트에는 Error(), SyntaxError(), TypeError() 등 여러 가지 에러 생성자가 내장되어 있으며 throw 문과 함께 사용된다.
이 생성자들을 통해 생성된 에러 객체들은 다음과 같은 프로퍼티를 가진다.

name
- 객체를 생성한 생성자 함수의 name 프로퍼티. 범용적인 'Error' 일 수도 있고 'RangError'와 같이 좀더 특화된 생성자일 수도 있다.

message
- 객체를 생성할 때 생성자에 전달된 문자열

throw문은 어떤 객체와도 함께 사용할 수 있다. 이 객체는 'name', 'message' 외에도 임의의 프로퍼티를 가질수 있기 때문에 catch문에서 처리할 정보를 담아 전달하면된다.

var num = 2;

try{
// 에러를 발생시킨다.
if(num === 2){
throw{
name : "MyErrorType", // 임의의 에러타입
message : "user message",
extra : "extra message",
remedy : genericErrorHandler // 에러 처리 함수
};
}
}catch(e){
// 사용자에게 공지
console.log(e.name);
console.log(e.message);
console.log(e.extra);

// 에러처리 함수 호출
e.remedy();
}
function genericErrorHandler(){
console.log('genericErrorHandler 입니다.');
}

/*
'MyErrorType'
'user message'
'extra message'
'genericErrorHandler 입니다.'
*/



아래와 같이 Error type 별로 세분화 할 수 있다.

try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}


+ Recent posts