JSON.stringify を使用してエラー インスタンスをシリアル化しようとすると、空のオブジェクトが返されます。この動作は、エラーの非表示のプロパティ記述子が原因で発生します。
Why JSON.stringify Fails:
エラー インスタンスのプロパティ記述子は 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