-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
34 lines (27 loc) · 937 Bytes
/
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
const format = require('string-template')
const path = require('path')
const caller = require('caller')
const fs = require('fs')
class CustomError extends Error {
constructor(code, message, context) {
super()
this.name = code
this.message = message
this.context = context
}
}
function init(filepath) {
const errorsPath = path.resolve(path.dirname(caller()), filepath)
const errorsText = fs.readFileSync(errorsPath, 'utf8')
const errorsData = JSON.parse(errorsText)
return function(code, context) {
const error = errorsData[code]
const message = format(error.msg, context)
const customError = new CustomError(code, message, context)
customError.stack = customError.stack.split('\n')
customError.stack.splice(1, 1)
customError.stack = customError.stack.join('\n')
return customError
}
}
module.exports = init