Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[tfjs-core] do not hang on invalid browser files #8517

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions tfjs-core/src/io/browser_files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,15 @@ class BrowserFiles implements IOHandler {
return new Promise((resolve, reject) => {
const jsonReader = new FileReader();
jsonReader.onload = (event: Event) => {
// tslint:disable-next-line:no-any
const modelJSON = JSON.parse((event.target as any).result) as ModelJSON;
let modelJSON: ModelJSON;
try {
// tslint:disable-next-line:no-any
modelJSON = JSON.parse((event.target as any).result);
} catch {
reject(new Error(`Failed to parse file ${
this.jsonFile.name}: {e.message}`));
return;
}

const modelTopology = modelJSON.modelTopology;
if (modelTopology == null) {
Expand Down
8 changes: 8 additions & 0 deletions tfjs-core/src/io/browser_files_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -677,4 +677,12 @@ describeWithFlags('browserFiles', BROWSER_ENVS, () => {
expect(() => tf.io.browserFiles(null)).toThrowError(/at least 1 file/);
expect(() => tf.io.browserFiles([])).toThrowError(/at least 1 file/);
});

it('Invalid JSON leads to Error', async () => {
const file = new File(['invalid'], 'model.json', {
type: 'application/json',
});
const filesHandler = tf.io.browserFiles([file]);
await expectAsync(filesHandler.load()).toBeRejectedWithError(/parse file/);
});
});