forked from ianstormtaylor/superstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
/
custom-errors.js
45 lines (38 loc) · 947 Bytes
/
custom-errors.js
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 { assert, number, object, string } from 'superstruct'
// Define a struct to validate with.
const User = object({
id: number(),
name: string(),
email: string(),
})
// Define data to be validated.
const data = {
id: 1,
name: true,
email: '[email protected]',
}
// Validate the data. In this case the `name` property is invalid, so an error
// will be thrown that you can catch and customize to your needs.
try {
assert(data, User)
} catch (e) {
const { key, value, type } = e
if (value === undefined) {
const error = new Error(`user_${key}_required`)
error.attribute = key
throw error
}
if (type === 'never') {
const error = new Error(`user_attribute_unknown`)
error.attribute = key
throw error
}
const error = new Error(`user_${key}_invalid`)
error.attribute = key
error.value = value
throw error
}
// Error: 'user_name_invalid' {
// attribute: 'name',
// value: false,
// }