class Rescue {
constructor (code, errors) {
this.code = code
this.errors = errors
}
}
const Tree = require('./tree')
const Parse = require('./parse')
const Compile = require('./compile')
const Find = require('./find')
function rescue (error, pattern) {
const patterns = function () {
if (Array.isArray(pattern)) {
return { rescue: Compile(Parse(pattern)) }
}
const parsed = {}
for (const code in pattern) {
parsed[code] = Compile(Parse(pattern[code]))
}
return parsed
} ()
const f = function (error) {
for (const code in patterns) {
const compiled = patterns[code]
const tree = Tree(error)
const found = Find(compiled.match, compiled.dive, compiled.test, tree)
if (found != null) {
return new Rescue(code, found.map(id => tree.ordered[tree.nodes[id].index]))
}
}
throw error
}
if (error === rescue) {
return f
}
return f(error)
}
module.exports = rescue