enhancement(schematics): include path in json parsing error message (#1048)

This commit is contained in:
Jason Jean 2019-02-12 12:43:21 -05:00 committed by GitHub
parent 0bbcacd954
commit 328aaab67a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 2 deletions

View File

@ -0,0 +1,37 @@
import { readJsonInTree } from './ast-utils';
import { SchematicTestRunner } from '@angular-devkit/schematics/testing';
import { join } from 'path';
import { Tree } from '@angular-devkit/schematics';
import { serializeJson } from './fileutils';
describe('readJsonInTree', () => {
let tree: Tree;
beforeEach(() => {
tree = Tree.empty();
});
it('should read JSON from the tree', () => {
tree.create(
'data.json',
serializeJson({
data: 'data'
})
);
expect(readJsonInTree(tree, 'data.json')).toEqual({
data: 'data'
});
});
it('should throw an error if the file does not exist', () => {
expect(() => readJsonInTree(tree, 'data.json')).toThrow(
'Cannot find data.json'
);
});
it('should throw an error if the file cannot be parsed', () => {
tree.create('data.json', `{ data: 'data'`);
expect(() => readJsonInTree(tree, 'data.json')).toThrow(
'Cannot parse data.json: Unexpected token d in JSON at position 2'
);
});
});

View File

@ -577,8 +577,12 @@ export function readJsonInTree<T = any>(host: Tree, path: string): T {
if (!host.exists(path)) {
throw new Error(`Cannot find ${path}`);
}
return JSON.parse(stripJsonComments(host.read(path)!.toString('utf-8')));
const contents = host.read(path)!.toString('utf-8');
try {
return JSON.parse(contents);
} catch (e) {
throw new Error(`Cannot parse ${path}: ${e.message}`);
}
}
/**