예외가 발생했을 때 어떤 예외가 발생했는지 정보를 함께 전달 받을수 있도록 한다.
예외 객체는 다음과 같이 catch구문의 괄호 안에 들어 있는 변수를 나타낸다.
마음대로 이름을 붙일 수 있지만 주로 e, exception 을 사용한다.
try{
} catch(exception){
}
예외 객체에는 name속성과, message속성이 있다.
try{
error.error.error(); //강제 예외 발생
} catch(e){
console.log(e.name);
console.log(e.message);
}
실행 결과
ReferenceError
error is not defined
예외를 강제로 발생 시키는 방법
아래와 같이 throw 키워드 뒤에 문자열 또는 Error객체를 입력한다.
throw '강제 예외';
좀 더 자세하게 예외를 출력하고 싶을 때는 Error객체를 사용한다.
const error = new Error('메세지');
error.name = '내 마음대로 오류';
error.message = '오류의 메세지';
throw error;
실행 결과
throw error;
^
내 마음대로 오류: 오류의 메세지
// +아래부분은 개인마다 다르다.
at Object. (D:\javaScript\RESTful\test.js:1:15)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint as runMain
at node:internal/main/run_main_module:23:47