Skip to content

Commit 7417e91

Browse files
authored
fix: report relevant error on invalid jsons (#80)
1 parent ca0f50b commit 7417e91

File tree

2 files changed

+38
-2
lines changed

2 files changed

+38
-2
lines changed

src/config.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,20 @@ const getConfiguration = ({ constants, inputs } = {}) => {
3838
(inputs && inputs.thresholds) || process.env.THRESHOLDS || {};
3939

4040
if (typeof thresholds === 'string') {
41-
thresholds = JSON.parse(thresholds);
41+
try {
42+
thresholds = JSON.parse(thresholds);
43+
} catch (e) {
44+
throw new Error(`Invalid JSON for 'thresholds' input: ${e.message}`);
45+
}
4246
}
4347

4448
let audits = (inputs && inputs.audits) || process.env.AUDITS;
4549
if (typeof audits === 'string') {
46-
audits = JSON.parse(audits);
50+
try {
51+
audits = JSON.parse(audits);
52+
} catch (e) {
53+
throw new Error(`Invalid JSON for 'audits' input: ${e.message}`);
54+
}
4755
}
4856

4957
if (!Array.isArray(audits)) {

src/config.test.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,4 +137,32 @@ describe('config', () => {
137137
audits: [{ path: 'PUBLISH_DIR/a/b', thresholds: {} }],
138138
});
139139
});
140+
141+
it('should throw error on invalid thresholds json input', () => {
142+
const constants = { THRESHOLDS: 'PUBLISH_DIR' };
143+
const inputs = {
144+
thresholds: 'invalid_json',
145+
audits: [{}],
146+
};
147+
148+
expect(() => getConfiguration({ constants, inputs })).toThrow(
149+
new Error(
150+
`Invalid JSON for 'thresholds' input: Unexpected token i in JSON at position 0`,
151+
),
152+
);
153+
});
154+
155+
it('should throw error on invalid audits json input', () => {
156+
const constants = { THRESHOLDS: 'PUBLISH_DIR' };
157+
const inputs = {
158+
thresholds: { performance: 1 },
159+
audits: 'invalid_json',
160+
};
161+
162+
expect(() => getConfiguration({ constants, inputs })).toThrow(
163+
new Error(
164+
`Invalid JSON for 'audits' input: Unexpected token i in JSON at position 0`,
165+
),
166+
);
167+
});
140168
});

0 commit comments

Comments
 (0)