"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > 오류를 직렬화할 때 JSON.stringify가 빈 개체를 반환하는 이유는 무엇입니까?

오류를 직렬화할 때 JSON.stringify가 빈 개체를 반환하는 이유는 무엇입니까?

2025-01-21에 게시됨
검색:804

Why Does JSON.stringify Return an Empty Object When Serializing an Error?

JSON.stringify를 사용하여 오류를 문자열화하는 것이 불가능합니까?

JSON.stringify를 사용하여 오류 인스턴스를 직렬화하려고 하면 빈 개체가 생성됩니다. 이 동작은 오류의 숨겨진 속성 설명자에서 발생합니다.

JSON.stringify가 실패하는 이유:

오류 인스턴스의 속성 설명자는 enumerable: false로 설정되어 오류가 발생하는 것을 방지합니다. 속성이 문자열화에 포함되지 않도록 합니다.

속성 탐색 및 설명자:

const error = new Error('sample message');
const propertyNames = Object.getOwnPropertyNames(error);
propertyNames.forEach(property => console.log(property, Object.getOwnPropertyDescriptor(error, property)));

Output:

stack { get: [Function], set: [Function], enumerable: false, configurable: true }
arguments { value: undefined, writable: true, enumerable: false, configurable: true }
type { value: 'custom message', writable: true, enumerable: false, configurable: true }
message { value: 'custom message', writable: true, enumerable: false, configurable: true }

Object.getOwnPropertyNames를 사용한 해결 방법:

에 오류 속성을 포함하려면 문자열화하려면 JSON.stringify(err, Object.getOwnPropertyNames(err))를 사용하세요. 이는 열거할 수 없는 속성에 대한 액세스를 제공합니다.

const serializedError = JSON.stringify(error, Object.getOwnPropertyNames(error));

추가 해결 방법:

  • 사용자 정의 오류 객체: 원하는 속성을 가진 사용자 정의 오류 객체를 생성하고 직렬화합니다.
  • 속성 추출: error.stack 및 error.message를 사용하여 수동으로 특정 오류 속성을 추출합니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3