Skip to content

Commit dc72617

Browse files
authored
[tfjs-core] do not hang on invalid browser files (#8517)
`tf.io.browserFiles` doesn't fail when loading invalid files. or rather, it fails, but never rejects the promise, making the `IOHandler.load` hang forever. wrapping the `JSON.parse` call in a try/catch and rejecting accordingly did the trick. and a small test to try it out. note: `FileReader.readAsText()` is a callback way to go around reading files. the promise-based `Blob.text()` would make `BrowserFile.load` simpler and safer (but felt ouf-of-scope here).
1 parent a83539d commit dc72617

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

tfjs-core/src/io/browser_files.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -139,8 +139,15 @@ class BrowserFiles implements IOHandler {
139139
return new Promise((resolve, reject) => {
140140
const jsonReader = new FileReader();
141141
jsonReader.onload = (event: Event) => {
142-
// tslint:disable-next-line:no-any
143-
const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;
142+
let modelJSON: ModelJSON;
143+
try {
144+
// tslint:disable-next-line:no-any
145+
modelJSON = JSON.parse((event.target as any).result);
146+
} catch {
147+
reject(new Error(`Failed to parse file ${
148+
this.jsonFile.name}: {e.message}`));
149+
return;
150+
}
144151

145152
const modelTopology = modelJSON.modelTopology;
146153
if (modelTopology == null) {

tfjs-core/src/io/browser_files_test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -677,4 +677,12 @@ describeWithFlags('browserFiles', BROWSER_ENVS, () => {
677677
expect(() => tf.io.browserFiles(null)).toThrowError(/at least 1 file/);
678678
expect(() => tf.io.browserFiles([])).toThrowError(/at least 1 file/);
679679
});
680+
681+
it('Invalid JSON leads to Error', async () => {
682+
const file = new File(['invalid'], 'model.json', {
683+
type: 'application/json',
684+
});
685+
const filesHandler = tf.io.browserFiles([file]);
686+
await expectAsync(filesHandler.load()).toBeRejectedWithError(/parse file/);
687+
});
680688
});

0 commit comments

Comments
 (0)