mirror of
https://github.com/mozilla/gecko-dev.git
synced 2024-10-27 12:15:33 +00:00
Bug 1370752: Part 2 - Allow fallback serializer when JSON.serialize fails. r=aswan
Currently, we need to be able to handle serializing non-JSON-compatible objects without catastrophically failing to save the storage file. Ideally, we would ensure this in the ordinary toJSON method. However, that would require a unnecessary extra calls to JSON.stringify for each object that needs to be sanitized before returning a JSON-safe value, which is more expensive than we can afford. The fallback toJSONSafe method allows us to do this only when necessary, due to an initial failed JSON serialization. MozReview-Commit-ID: JXQ001dOGtW --HG-- extra : rebase_source : 0b7b388316fdc464b47cdd4f7d8c70bc906a9c27
This commit is contained in:
parent
bded2d68fd
commit
45acce829f
@ -286,8 +286,20 @@ JSONFile.prototype = {
|
|||||||
* @rejects JavaScript exception.
|
* @rejects JavaScript exception.
|
||||||
*/
|
*/
|
||||||
async _save() {
|
async _save() {
|
||||||
|
let json;
|
||||||
|
try {
|
||||||
|
json = JSON.stringify(this._data);
|
||||||
|
} catch (e) {
|
||||||
|
// If serialization fails, try fallback safe JSON converter.
|
||||||
|
if (typeof this._data.toJSONSafe == "function") {
|
||||||
|
json = JSON.stringify(this._data.toJSONSafe());
|
||||||
|
} else {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Create or overwrite the file.
|
// Create or overwrite the file.
|
||||||
let bytes = gTextEncoder.encode(JSON.stringify(this._data));
|
let bytes = gTextEncoder.encode(json);
|
||||||
if (this._beforeSave) {
|
if (this._beforeSave) {
|
||||||
await Promise.resolve(this._beforeSave());
|
await Promise.resolve(this._beforeSave());
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user