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));
추가 해결 방법:
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3