Skip to content

Commit

Permalink
fix: throw custom YamlParseError while yaml parse
Browse files Browse the repository at this point in the history
  • Loading branch information
yarastqt committed Oct 26, 2020
1 parent bf3ad5f commit a16bbf4
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/core/yaml-interop.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,36 @@
import Module from 'module'
import { readFileSync } from 'fs'
import YAML from 'yaml'
import { codeFrameColumns } from '@babel/code-frame'

class YamlParseError extends Error {
public location: any

constructor(fileName: string, source: string, message: string, location: any) {
super('')
// Override native stack with custom message.
this.stack = new Error(
[
// Take only message without code-frame.
`${message.split(/\n/)[0]} (${fileName}:${location.start.line}:${location.start.col})`,
codeFrameColumns(source, {
start: { line: location.start.line, column: location.start.col },
}),
].join('\n'),
).stack
this.location = location
}
}

Module.prototype.require = new Proxy(Module.prototype.require, {
apply(target, thisArg, args) {
if (/\.ya?ml$/.test(args[0])) {
const file = readFileSync(args[0], 'utf8')
try {
return YAML.parse(file)
} catch (error) {}
return YAML.parse(file, { prettyErrors: true })
} catch (error) {
throw new YamlParseError(args[0], file, error.message, error.linePos)
}
}
return Reflect.apply(target, thisArg, args)
},
Expand Down

0 comments on commit a16bbf4

Please sign in to comment.