develop
Error 객체 JSON.stringify()
yogae
2020. 3. 20. 15:13
Error 객체를 JSON.stringify()하면 error message, stack field가 사라진다.
const err = new Error('test');
console.log(JSON.stringify(err)); // {}
객체의 속성들은 그 자체로 객체 내부의 정보와 기능을 표현하지만, 각 속성들은 다시 그 자신들의 값과 성질에 대한 눈에 보이지않는 내부 속성들을 가지고 있습니다. 자바스크립트에서는 이러한 속성의 세부적인 성질을 직접 설정하거나 조회할 수 있는 방법을 제공하는데, 이 때 이용되는 특수한 객체가 바로 속성 설명자(PropertyDescriptor) 이다.
var error = new Error(‘test');
var propertyNames = Object.getOwnPropertyNames(error);
var descriptor;
for (i = 0; i < propertyNames.length ; ++i) {
property = propertyNames[i];
descriptor = Object.getOwnPropertyDescriptor(error, property);
console.log(property, descriptor)
}
// stack {
// value: … stack 정보,
// writable: true,
// enumerable: false,
// configurable: true }
// message {
// value: ‘test’,
// writable: true,
// enumerable: false,
// configurable: true }
property descriptors는 다음과 같은 키를 공유한다.
- _configurable_이 속성의 값을 변경할 수 있고, 대상 객체에서 삭제할 수도 있다면 true. 기본값은false.
- _enumerable_이 속성이 대상 객체의 속성 열거 시 노출된다면 true. 기본값은false.
- writable 할당 연산자로 속성의 값을 바꿀 수 있다면 true. 기본값은false.
- _value_속성에 연관된 값. 아무 유효한 JavaScript 값(숫자, 객체, 함수 등)이나 가능합니다. 기본값은 undefined
Error 객체의 enumerable false로 설정한 property는 JSON.stringify()
를 호출했을 때 제외된다.
getOwnPropertyNames()
를 사용하여 enumerable false로 설정된 properties들도 반환하게 된다.
Reference