-
Notifications
You must be signed in to change notification settings - Fork 221
/
error.ts
47 lines (43 loc) · 1.26 KB
/
error.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
46
47
/**
* A `StructFailure` represents a single specific failure in validation.
*/
export type Failure = {
value: any
key: any
type: string
refinement: string | undefined
message: string
branch: Array<any>
path: Array<any>
}
/**
* `StructError` objects are thrown (or returned) when validation fails.
*
* Validation logic is design to exit early for maximum performance. The error
* represents the first error encountered during validation. For more detail,
* the `error.failures` property is a generator function that can be run to
* continue validation and receive all the failures in the data.
*/
export class StructError extends TypeError {
value: any
key!: any
type!: string
refinement!: string | undefined
path!: Array<any>
branch!: Array<any>
failures: () => Array<Failure>;
[x: string]: any
constructor(failure: Failure, failures: () => Generator<Failure>) {
let cached: Array<Failure> | undefined
const { message, ...rest } = failure
const { path } = failure
const msg =
path.length === 0 ? message : `At path: ${path.join('.')} -- ${message}`
super(msg)
Object.assign(this, rest)
this.name = this.constructor.name
this.failures = () => {
return (cached ??= [failure, ...failures()])
}
}
}