UNPKG

1.38 kBJavaScriptView Raw
1'use strict'
2
3/**
4 * @class
5 * @param {string} message
6 * @param {Header|Obj} [...el] The element(s) that caused the error
7 * @extends Error
8 */
9function ParseError(message) {
10 Error.call(this)
11
12 /** @member {string} */
13 this.message = message
14
15 /** @member {Array<Header|Obj>} */
16 this.els = [].slice.call(arguments, 1).filter(Boolean)
17}
18
19require('util').inherits(ParseError, Error)
20
21/**
22 * Log the original code region that caused the error into the console
23 * @param {string[]} originalLines
24 */
25ParseError.prototype.logSourceContext = function (originalLines) {
26 var start = Infinity,
27 end = -Infinity,
28 str = '\n-----',
29 i, focus, checkElFocus, lineNum
30
31 if (!this.els.length) {
32 return
33 }
34 this.els.forEach(function (el) {
35 start = Math.min(start, el.source.begin)
36 end = Math.max(end, el.source.end)
37 })
38
39 checkElFocus = function (el) {
40 return i >= el.source.begin && i < el.source.end
41 }
42
43 for (i = Math.max(0, start - 3); i < end + 3 && i < originalLines.length; i++) {
44 focus = this.els.some(checkElFocus)
45 lineNum = String(i + 1)
46 while (lineNum.length < 3) {
47 lineNum = ' ' + lineNum
48 }
49 str += '\n\x1b[32m' + lineNum + '\x1b[0m '
50 str += (focus ? '\x1b[31;1m>' : ' ') + ' ' + originalLines[i] + (focus ? '\x1b[0m' : '')
51 }
52 str += '\n-----'
53
54 console.log(str)
55}
56
57module.exports = ParseError
\No newline at end of file