enhancement(schematics): include path in json parsing error message (#1048)
This commit is contained in:
parent
0bbcacd954
commit
328aaab67a
37
packages/schematics/src/utils/ast-utils.spec.ts
Normal file
37
packages/schematics/src/utils/ast-utils.spec.ts
Normal 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'
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -577,8 +577,12 @@ export function readJsonInTree<T = any>(host: Tree, path: string): T {
|
|||||||
if (!host.exists(path)) {
|
if (!host.exists(path)) {
|
||||||
throw new Error(`Cannot find ${path}`);
|
throw new Error(`Cannot find ${path}`);
|
||||||
}
|
}
|
||||||
|
const contents = host.read(path)!.toString('utf-8');
|
||||||
return JSON.parse(stripJsonComments(host.read(path)!.toString('utf-8')));
|
try {
|
||||||
|
return JSON.parse(contents);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Cannot parse ${path}: ${e.message}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user