/
formatErrors.ts
45 lines (42 loc) 路 1.37 KB
/
formatErrors.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import {ErrorObject} from 'ajv';
/**
* Formats an array of schema validation errors.
* @param errors An array of error messages to format.
* @returns Formatted error message
* Based on https://github.com/eslint/eslint/blob/master/lib/shared/config-validator.js#L237-L261
*/
export function formatErrors(errors: ErrorObject[]): string {
return errors
.map((error) => {
if (
error.keyword === 'additionalProperties' &&
'additionalProperty' in error.params
) {
const formattedPropertyPath = error.dataPath.length
? `${error.dataPath.slice(1)}.${error.params.additionalProperty}`
: error.params.additionalProperty;
return `Unexpected top-level property "${formattedPropertyPath}"`;
}
if (error.keyword === 'type') {
const formattedField = error.dataPath.slice(1);
if (!formattedField) {
return `Config has the wrong type - ${error.message}`;
}
return `Property "${formattedField}" has the wrong type - ${error.message}`;
}
const field =
(error.dataPath[0] === '.'
? error.dataPath.slice(1)
: error.dataPath) || 'Config';
if (error.keyword === 'typeof') {
return `"${field}" should be a ${error.schema}. Value: ${JSON.stringify(
error.data
)}`;
}
return `"${field}" ${error.message}. Value: ${JSON.stringify(
error.data
)}`;
})
.map((message) => `\t- ${message}.\n`)
.join('');
}