From a16bbf43b88c9ffdd1c95014870da7e70a7505e1 Mon Sep 17 00:00:00 2001 From: Eugene Date: Mon, 26 Oct 2020 18:02:38 +0300 Subject: [PATCH] fix: throw custom YamlParseError while yaml parse --- src/core/yaml-interop.ts | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/core/yaml-interop.ts b/src/core/yaml-interop.ts index 084ba5c..f1c6883 100644 --- a/src/core/yaml-interop.ts +++ b/src/core/yaml-interop.ts @@ -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) },