개발

Error 객체를 JSON.stringify에 넣으면 빈객체가 출력되는건에 대하여

dohye1 2024. 4. 27. 15:13
반응형

해결책

const testError = new Error("this is Error");

JSON.stringify(testError, Object.getOwnPropertyNames(testError))

 

아래 내용은 위의 해결책 코드가 어떻게 동작하는지에 대한 정리입니다.

해결책만 원하신다면 위에있는코드를 참고하시면됩니당~

상황

try~ catch구문을 사용할때 catch의 인자로 넘어오는 error 객체를 stringify해서 다른 페이지로 전달해줘야했는데,

JSON.stringify()에 error 객체를 넘겨주면 빈 객체가 출력됨

 

일단 console 창에서 error 객체의 출력을  테스트해봤다

const testError = new Error("this is Error");

 

해당 에러 객체가 있을때

1. console.log

문자열 형태로 객체가 출력됨

2. console.dir

3. console.table

 

그런데 JSON.stringify를 했을때는 아래처럼 출력된다...!!!!!!

 

 

원인

우선 JSON.stringify 메서드에 대해 살펴보자

 

JSON.stringify() - JavaScript | MDN

JSON.stringify() 메서드는 JavaScript 값이나 객체를 JSON 문자열로 변환합니다. 선택적으로, replacer를 함수로 전달할 경우 변환 전 값을 변형할 수 있고, 배열로 전달할 경우 지정한 속성만 결과에 포함

developer.mozilla.org

mdn을 보면 JSON.stringify()는 기본적으로 열거가능한 프로퍼티(enumerable property)만 처리한다.

 

그리고 Error 객체의 모든 프로퍼티는 

{ [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

이런 속성을 가진다.

 

 

ECMAScript® 2025 Language Specification

Historically, this method was occasionally used to access the String value of the [[Class]] internal slot that was used in previous editions of this specification as a nominal type tag for various built-in objects. The above definition of toString preserve

tc39.es

 

그럼 결론적으로 error 객체의 모든 필드는 enumerable이 false이고, JSON.stringify()는 enumerable한 필드에 대해서만 처리가 되므로 에러객체가 빈 객체로 출력이 될 수 밖에없다.

해결책

해결책을 구글링해보니 Object.getOwnPropertyNames() 메서드를 사용하면된다고한다..!!

그럼 구체적으로 어떻게 돌아가는지 파헤쳐보자

 

일단 Object.getOwnPropertyNames() 메서드의 역할을 보면 

non-enumerable properties를 포함한 모든 프로퍼티를 배열로 반환한다고한다.

 

그럼 에러 객체를 인자로 넘겨서 출력해보면 아래처럼 나온다!

 

오 신기하고만,,,!!!

 

그럼 저 값을 사용해서 어떻게 error를 stirngify에 포함이되도록하는지 보면

JSON.stringify에 두번째 인자로 내가 읽고싶은 필드명을 넘겨주면된다!

그래서 아래처럼 코드를 출력해보면

JSON.stringify(testError, Object.getOwnPropertyNames(testError))

내가 읽고싶은 정보들이 모두 나온다!

 

 

추가

JSON.stringify처럼 enumerable한 값만 처리하는 메서드를 좀 더 찾아보았다.

 

Object.keys()

Object.entries()

Object.values()

...