/
index.js
52 lines (44 loc) · 1.11 KB
/
index.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
46
47
48
49
50
51
52
const { format } = require('util')
module.exports = function(errors) {
return class extends Error {
constructor(code, ...args) {
if (code.constructor === Object) {
// new E(json)
const e = code
super(e.message)
Object.defineProperty(this, 'httpStatus', {
value: errors[e.code].httpStatus,
enumerable: false
})
for (const p in e) {
if (p !== 'message') this[p] = e[p]
}
} else {
// new E(code, ...formatParams, props)
let props = args[args.length - 1]
if (props && props.constructor === Object) {
args.pop()
} else {
props = null
}
super(format(errors[code].message, ...args))
Object.defineProperty(this, 'httpStatus', {
value: errors[code].httpStatus,
enumerable: false
})
this.code = code
if (props) {
for (const k in props) {
this[k] = props[k]
}
}
}
}
toJSON() {
return {
message: this.message,
...this
}
}
}
}