UNPKG

2.59 kBJavaScriptView Raw
1
2/**
3 * Define a base error class to extend.
4 *
5 * @type {StructError}
6 */
7
8class StructError extends Error {
9
10 constructor(message, data) {
11 super(message)
12 this.name = 'StructError'
13
14 for (const key in data) {
15 this[key] = data[key]
16 }
17
18 Error.captureStackTrace(this, this.constructor)
19 }
20
21}
22
23/**
24 * Define specific errors.
25 *
26 * @type {StructError}
27 */
28
29class ElementInvalidError extends StructError {
30
31 constructor({ type, index, value, path = [] }) {
32 const message = `The element at \`${index}\` in an array was invalid. It should be of type "${type}", but it was: ${value}`
33 const code = 'element_invalid'
34 super(message, { code, type, path, index, value })
35 Error.captureStackTrace(this, this.constructor)
36 }
37
38}
39
40class PropertyInvalidError extends StructError {
41
42 constructor({ type, key, value, path = [] }) {
43 const message = `The \`${key}\` property in an object was invalid. It should be of type "${type}", but it was: ${value}`
44 const code = 'property_invalid'
45 super(message, { code, type, path, key, value })
46 Error.captureStackTrace(this, this.constructor)
47 }
48
49}
50
51class PropertyRequiredError extends StructError {
52
53 constructor({ type, key, path = [] }) {
54 const message = `The \`${key}\` property is required but was not defined. It should be of type "${type}".`
55 const code = 'property_required'
56 super(message, { code, type, path, key })
57 Error.captureStackTrace(this, this.constructor)
58 }
59
60}
61
62class PropertyUnknownError extends StructError {
63
64 constructor({ key, path = [] }) {
65 const message = `The \`${key}\` property in an object was not recognized.`
66 const code = 'property_unknown'
67 super(message, { code, path, key })
68 Error.captureStackTrace(this, this.constructor)
69 }
70
71}
72
73class ValueInvalidError extends StructError {
74
75 constructor({ type, value, path = [] }) {
76 const message = `Expected the value "${value}" to match type "${type}".`
77 const code = 'value_invalid'
78 super(message, { code, type, path, value })
79 Error.captureStackTrace(this, this.constructor)
80 }
81
82}
83
84class ValueRequiredError extends StructError {
85
86 constructor({ type, path = [] }) {
87 const message = `A required property was not defined. It should be of type "${type}".`
88 const code = 'value_required'
89 super(message, { code, type, path })
90 Error.captureStackTrace(this, this.constructor)
91 }
92
93}
94
95/**
96 * Export.
97 *
98 * @type {Object}
99 */
100
101export {
102 ElementInvalidError,
103 PropertyInvalidError,
104 PropertyRequiredError,
105 PropertyUnknownError,
106 ValueInvalidError,
107 ValueRequiredError,
108}
109